wordpress get_results($sql, ARRAY_A) query comments has duplicate comment - sql

When using get_results($sql, ARRAY_A) to query wp_comments, there is a comment in the result.
The sql is below
SELECT comment_ID,comment_parent,comment_author,comment_author_url,comment_author_email,comment_content,comment_date,comment_type,ck_rating_up,ck_rating_down
FROM $wpdb->comments
LEFT JOIN $comment_rating_table
ON ($wpdb->comments.comment_ID = $comment_rating_table.ck_comment_id)
WHERE comment_post_ID = $post_id AND comment_approved = 1
order by comment_id ASC
How to avoid duplicate comments?

The question being asked is, how to get the results containing no duplicates. Since nothing was mentioned as to which field, I will assume it's the main comments field which is of type text, which means you can't use DISTINCT on it.
However since this field contains comments and not novels worth of text, then really there should be no reason for a comment field to be of type text at all. So what needs to happen is for the field to be convert from type text to type varchar, and use (max) as the field size.
The varchar(max) field can hold 64k of data, which is about 10,000-20,000 words depending on the alphabet used. This should be more than enough room to hold a 40 page essay or a single comment.
As for the SQL:
SELECT comment_ID,comment_parent,comment_author,comment_author_url,comment_author_email,comment_content,comment_date,comment_type,ck_rating_up,ck_rating_down
FROM $wpdb->comments
LEFT JOIN $comment_rating_table
ON ($wpdb->comments.comment_ID = $comment_rating_table.ck_comment_id)
WHERE comment_post_ID = $post_id
AND comment_approved = 1
AND comment_ID IN (SELECT DISTINCT( comment_content ) FROM $wpdb->comments
LEFT JOIN $comment_rating_table
ON ($wpdb->comments.comment_ID = $comment_rating_table.ck_comment_id)
WHERE comment_post_ID = $post_id AND comment_approved = 1)
order by comment_id ASC
A faster option is instead of DISTINCT to use GROUP BY comment_content , and then selecting either the MIN or MAX
SELECT comment_ID,comment_parent,comment_author,comment_author_url,comment_author_email,comment_content,comment_date,comment_type,ck_rating_up,ck_rating_down
FROM $wpdb->comments
LEFT JOIN $comment_rating_table(
SELECT MAX(comment_id) AS id FROM comment GROUP BY comment_content
maxid ON ($wpdb->comments.comment_ID = $comment_rating_table.ck_comment_id) WHERE comment_post_ID = $post_id AND comment_approved = 1) order by comment_id ASC

Related

Get Distinct values from one table in a join query containing column data type like ntext

I have two tables
Review and ProjectsReview. I want to change the order by columns without impacting the result. Initial order by was on createdDate column from review table.
Initial query is as below.
SELECT
*
FROM Review r
WHERE (status IS NULL
OR fstatus = '')
AND (crBy = '100'
OR crByPr = '')
ORDER BY createdDate
The query returns 8 rows.
The user wants to change the order by using program name which is in another table. The query to get the same is as below.
SELECT
r.*
FROM Review r
INNER JOIN ProjectsReview rp
ON rp.rID = r.rID
WHERE (status IS NULL
OR fstatus = '')
AND (crBy = '100'
OR crByPr = '')
ORDER BY prNo, prName
This returns 10 rows. But the required result is only 8 rows and only columns of review table.
I cannot apply group by on all the columns from Review table since there are data types with image and ntext.
Is there a way to achieve this without inserting the data to a temp table and get distinct values.
Try this
with cte
as
(
select
rn = row_number() over(partition by rID order by prNo,prName),
rID,
prNo,
prName
from ProjectsReview
)
SELECT r.*
FROM Review r
inner join cte rp on rp.rID =r.rID
WHERE (status IS NULL OR fstatus = '') AND (crBy = '100' OR crByPr = '')
and cte.rn = 1
ORDER BY prNo,prName

Issue adding SQL FullText Search to an existing SELECT statement

I'm trying to do a full text search but am having issues implementing it. I have an Object which can have multiple "Titles". I have a stored procedure that takes a language and country and returns a normalized result with the best "Title" based on the localization.
What I want to be able to do is perform a full text search on the "Title" table that will search all rows but then only return the normalized, default title.
To get the normalized result I have something like
NORMALIZING STATEMENT
SELECT MainObject.*, Title.Name, Description.Name
FROM MainObject
OUTER APPLY
(
SELECT TOP 1 Title.Name
FROM Title
WHERE Title.MainObject_ID = MainObject.ID AND Title.Language = #language
ORDER BY Title.[Default] DESC
)
OUTER APPLY
(
SELECT TOP 1 Description.Name
FROM Description
WHERE Description.MainObject_ID = MainObject.ID AND Description.Language = #language
ORDER BY Description.[Default] DESC
)
Say an object has 3 titles, Alpha, Bravo and Charlie with Alpha being the default Title.
I want to be able to do a full text search for Bravo. The object that Bravo is linked to is found but is normalized with the above statement. I.E search for "Bravo" and "Alpha" is returned as Title.Name.
The only way I can think of doing this is to first perform the Search such as
FULL-TEXT STATEMENT
SELECT Title.MainObject_ID, MAX(KEY_TBL.RANK)
FROM Title
INNER JOIN
FREETEXTTABLE(Title,Name,'Some Search') AS KEY_TBL
ON Title.ID = KEY_TBL.[KEY]
WHERE KEY_TBL.RANK >= 50
GROUP BY Title.MainObjectID, KEY_TBL.RANK
ORDER BY KEY_TBL.RANK DESC
This returns a list of MainObjects. I can then run these through the top statement. Is there a way to combine the two in a more elegant manor to thus get better performance?
UPDATE:
I can perform a WHERE IN on the full text statement but I'm not sure how to get the RANK back out to the main statement so I can have final output ordered by descending RANK.
NORMALIZING STATEMENT
WHERE MainObject.ID IN
(
FULL-TEXT STATEMENT
)
I got there in the end.... I started with the full text search on the "title" Table, then joined this back to the MainObject Table and carried on from there. I have to group by everything I want to select.
SELECT MainObject.ID, MAX(KEY_TBL.RANK) AS IndexRank, MainObject.OtherColumns, Title.Name, Description.Name
FROM Title AS FT_TBL
INNER JOIN
FREETEXTTABLE(Title,Name,'Some Search') AS KEY_TBL
ON FT_TBL.ID = KEY_TBL.[KEY]
INNER JOIN
MainObject ON FT_TBL.MainObjectID = MainObject.ID
OUTER APPLY
(
SELECT TOP 1 Title.Name
FROM Title
WHERE Title.MainObject_ID = MainObject.ID AND Title.Language = #language
ORDER BY Title.[Default] DESC
)
OUTER APPLY
(
SELECT TOP 1 Description.Name
FROM Description
WHERE Description.MainObject_ID = MainObject.ID AND Description.Language = #language
ORDER BY Description.[Default] DESC
)
GROUP BY MainObject.ID, KEY_TBL.RANK, MainObject.OtherColumns, Title.Name, Description.Name
ORDER BY IndexRank desc

Providing Language FallBack In A SQL Select Statement

I have a table that represents an Object. It has many columns but also fields that require language support.
For simplicity let's say I have 3 tables:
MainObjectTable
LanguageDependantField1
LanguageDependantField2.
MainObjectTable has a PK int called ID, and both LanguageDependantTables have a foreign key link back to the MainObjectTable along with a language code and the date they were added.
I've created a stored procedure that accepts the MainObjectTable ID and a Language. It will return a single row containing the most recent items from the language tables. The select statement looks like
SELECT
MainObjectTable.VariousColumns,
LanguageDependantField1.Description,
LanguageDependantField2.SomeOtherText
FROM
MainObjectTable
OUTER APPLY
(SELECT TOP 1 LanguageDependantField1.Description
FROM LanguageDependantField1
WHERE LanguageDependantField1.MainObjectTable_ID = MainObjectTable.ID
AND LanguageDependantField1.Language_ID = #language
ORDER BY
LanguageDependantField1.[Default], LanguageDependantField1.CreatedDate DESC) LanguageDependantField1
OUTER APPLY
(SELECT TOP 1 LanguageDependantField2.SomeOtherText
FROM LanguageDependantField2
WHERE LanguageDependantField2.MainObjectTable_ID = MainObjectTable.ID
AND LanguageDependantField2.Language_ID = #language
ORDER BY
LanguageDependantField2.[Default] DESC, LanguageDependantField2.CreatedDate DESC) LanguageDependantField2
WHERE
MainObjectTable.ID = #MainObjectTableID
What I want to add is the ability to fallback to a default language if a row isn't found in the specified language. Let's say we use "German" as the selected language. Is it possible to return an English row from LanguageDependantField1 if the German does not exist presuming we have #fallbackLanguageID
Also am I right to use OUTER APPLY in this scenario or should I be using JOIN?
Many thanks for your help.
Try this:
SELECT MainObjectTable.VariousColumns,
COALESCE(PrefLang.Description,Fallback.Description,'Not Found Desc')
as Description,
COALESCE(PrefLang.SomeOtherText,FallBack.SomeOtherText,'Not found')
as SomeOtherText
FROM MainObjectTable
LEFT JOIN
(SELECT TOP 1 pl.Description,pl.SomeOtherText
FROM LanguageDependantField1 pl
WHERE pl.MainObjectTable_ID = MainObjectTable.ID
AND pl.Language_ID = #language
ORDER BY
pl.[Default], pl.CreatedDate DESC)
PrefLang ON 1=1
LEFT JOIN
(SELECT TOP 1 fb.Description,fb.SomeOtherText
FROM LanguageDependantField1 fb
WHERE fb.MainObjectTable_ID = MainObjectTable.ID
AND fb.Language_ID = #fallbackLanguageID
ORDER BY
fb.[Default], fb.CreatedDate DESC)
Fallback ON 1=1
WHERE
MainObjectTable.ID = #MainObjectTableID
Basically, make two queries, one to the preferred language and one to English (Default). Use the LEFT JOIN, so if the first one isn't found, the second query is used...
I don't have your actual tables, so there might be a syntax error in above, but hope it gives you the concept you want to try...
Yes, the use of Outer Apply is correct if you want to correlate the MainObjectTable table rows to the inner queries. You cannot use Joins with references in the derived table to the outer table. If you wanted to use Joins, you would need to include the joining column(s) and in this case pre-filter the results. Here is what that might look like:
With RankedLanguages As
(
Select LDF1.MainObjectTable_ID, LDF1.Language_ID, LDF1.Description, LDF1.SomeOtherText, ...
, Row_Number() Over ( Partition By LDF1.MainObjectTable_ID, LDF1.Language_ID
Order By LDF1.[Default] Desc, LDF1.CreatedDate Desc ) As Rnk
From LanguageDependantField1 As LDF1
Where LDF1.Language_ID In( #languageId, #defaultLanguageId )
)
Select M.VariousColumns
, Coalesce( SpecificLDF.Description, DefaultLDF.Description ) As Description
, Coalesce( SpecificLDF.SomeOtherText, DefaultLDF.SomeOtherText ) As SomeOtherText
, ...
From MainObjectTable As M
Left Join RankedLanguages As SpecificLDF
On SpecificLDF.MainObjectTable_ID = M.ID
And SpecifcLDF.Language_ID = #languageId
And SpecifcLDF.Rnk = 1
Left Join RankedLanguages As DefaultLDF
On DefaultLDF.MainObjectTable_ID = M.ID
And DefaultLDF.Language_ID = #defaultLanguageId
And DefaultLDF.Rnk = 1
Where M.ID = #MainObjectTableID

Doing an Update Ignore in SQL Server 2005

I have a table where I wish to update some of the rows. All the fields are not null. I'm doing a sub-query, and I wish to update the table with the non-Null results.
See Below for my final answer:
In MySQL, I solve this problem by doing an UPDATE IGNORE. How do I make this work in SQL Server 2005? The sub-query uses a four-table Join to find the data to insert if it exists. The Update is being run against a table that could have 90,000+ records, so I need a solution that uses SQL, rather than having the Java program that's querying the database retrieve the results and then update those fields where we've got non-Null values.
Update: My query:
UPDATE #SearchResults SET geneSymbol = (
SELECT TOP 1 symbol.name FROM
GeneSymbol AS symbol JOIN GeneConnector AS geneJoin
ON symbol.id = geneJoin.geneSymbolID
JOIN Result AS sSeq ON geneJoin.sSeqID = sSeq.id
JOIN IndelConnector AS joiner ON joiner.sSeqID = sSeq.id
WHERE joiner.indelID = #SearchResults.id ORDER BY symbol.id ASC)
WHERE isSNV = 0
If I add "AND symbol.name IS NOT NULL" to either WHERE I get a SQL error. If I run it as is I get "adding null to a non-null column" errors. :-(
Thank you all, I ended up finding this:
UPDATE #SearchResults SET geneSymbol =
ISNULL ((SELECT TOP 1 symbol.name FROM
GeneSymbol AS symbol JOIN GeneConnector AS geneJoin
ON symbol.id = geneJoin.geneSymbolID
JOIN Result AS sSeq ON geneJoin.sSeqID = sSeq.id
JOIN IndelConnector AS joiner ON joiner.sSeqID = sSeq.id
WHERE joiner.indelID = #SearchResults.id ORDER BY symbol.id ASC), ' ')
WHERE isSNV = 0
While it would be better not to do anything in the null case (so I'm going to try to understand the other answers, and see if they're faster) setting the null cases to a blank answer also works, and that's what this does.
Note: Wrapping the ISNULL (...) with () leads to really obscure (and wrong) errors.
with UpdatedGenesDS (
select joiner.indelID, name, row_number() over (order by symbol.id asc) seq
from
GeneSymbol AS symbol JOIN GeneConnector AS geneJoin
ON symbol.id = geneJoin.geneSymbolID
JOIN Result AS sSeq ON geneJoin.sSeqID = sSeq.id
JOIN IndelConnector AS joiner ON joiner.sSeqID = sSeq.id
WHERE name is not null ORDER BY symbol.id ASC
)
update Genes
set geneSymbol = upd.name
from #SearchResults a
inner join UpdateGenesDs upd on a.id = b.intelID
where upd.seq =1 and isSNV = 0
this handles the null completely as all are filtered out by the where predicate (can also be filtered by join predicate if You wish. Is it what You are looking for?
Here's another option, where only those rows in #SearchResults that are succesfully joined will be udpated. If there are no null values in the underlying data, then the inner joins will pull in no null values, and you won't have to worry about filtering them out.
UPDATE #SearchResults
set geneSymbol = symbol.name
from #SearchResults sr
inner join IndelConnector AS joiner
on joiner.indelID = sr.id
inner join Result AS sSeq
on sSeq.id = joiner.sSeqID
inner join GeneConnector AS geneJoin
on geneJoin.sSeqID = sSeq.id
-- Get "lowest" (i.e. first if listed alphabetically) value of name for each id
inner join (select id, min(name) name
from GeneSymbol
group by id) symbol
on symbol.id = geneJoin.geneSymbolID
where isSNV = 0 -- Which table is this value from?
(There might be some syntax problems, without tables I can't debug it)

selecting latest rows per distinct foreign key value

excuse the title, i couldn't come up with something short and to the point...
I've got a table 'updates' with the three columns, text, typeid, created - text is a text field, typeid is a foreign key from a 'type' table and created is a timestamp. A user is entering an update and select the 'type' it corresponds too.
There's a corresponding 'type' table with columns 'id' and 'name'.
I'm trying to end up with a result set with as many rows as is in the 'type' table and the latest value from updates.text for the particular row in types. So if i've got 3 types, 3 rows would be returned, one row for each type and the most recent updates.text value for the type in question.
Any ideas?
thanks,
John.
select u.text, u.typeid, u.created, t.name
from (
select typeid, max(created) as MaxCreated
from updates
group by typeid
) mu
inner join updates u on mu.typeid = u.typeid and mu.MaxCreated = u.Created
left outer join type t on u.typeid = t.typeid
What are the actual columns you want returned?
SELECT t.*,
y.*
FROM TYPE t
JOIN (SELECT u.typeid,
MAX(u.created) 'max_created'
FROM UPDATES u
GROUP BY u.typeid) x ON x.typeid = t.id
JOIN UPDATES y ON y.typeid = x.typeid
AND y.created = x.max_created
SELECT
TYP.id,
TYP.name,
TXT.comment
FROM
dbo.Types TYP
INNER JOIN dbo.Type_Comments TXT ON
TXT.type_id = TYP.id
WHERE
NOT EXISTS
(
SELECT
*
FROM
dbo.Type_Comments TXT2
WHERE
TXT2.type_id = TYP.id AND
TXT2.created > TXT.created
)
Or:
SELECT
TYP.id,
TYP.name,
TXT.comment
FROM
dbo.Types TYP
INNER JOIN dbo.Type_Comments TXT ON
TXT.type_id = TYP.id
LEFT OUTER JOIN dbo.Type_Comments TXT2 ON
TXT2.type_id = TYP.id AND
TXT2.created > TXT.created
WHERE
TXT2.type_id IS NULL
In either case, if the created date can be identical between two rows with the same type_id then you would need to account for that.
I've also assumed at least one comment per type exists. If that's not the case then you would need to make a minor adjustment for that as well.