EDIT : my question is not clear, so I've reformulated it here : Order sql result by occurrence of a set of keywords in a string
I'm improving my search system for my website. I'm trying to use and increment variables in sql request, like that...
SET #titlematch = 0;
SELECT *,
CASE
when title like '%apple%' then (SET #titlematch = #titlematch+1)
when title like '%orange%' then (SET #titlematch = #titlematch+1)
when title like '%other_keyword_searched%' then (SET #titlematch = #titlematch+1)
(...)
END,
(...)
FROM pages
(...)
ORDER by #titlematch desc
In fact, titlematch should be incremented each time that a keyword is in the title. If there's "apple" and "orange" in the title, titlematch should be equal to 2.
But actually, it doesn't work...
(sorry for my english)
I think it fails because it must handle all the data,if title like someWordYouDontAcccountFor it will fail.You must account for all possible cases or use else.
In response to your comment (Yes, always), I rewrite your query in this way:
SELECT *, (select count(*) from pages p2 where p1.field_date < p2.field_date) as pos
(...)
FROM pages p1
(...)
ORDER by (select count(*) from pages p2 where p1.field_date < p2.field_date) desc
In this way you count every rows before the actual (I've based my count on ipotetic field_date but if you want you can change your condition), so you have an incremental value for each row, and finally, I add this condition in order by clause.
Tell me if it's OK
Related
I've got a products table that I'm trying to get to work. The query brings back results; however, it isn't actually using the ORDER BY FIELD to sort the results. It's skipping it somehow. I even tried ORDER BY FIELD(sc.id,'4','5','6'), and that didn't work either.
Is it even possible to use table_name.column in an ORDER BY FIELD()? Is there an alternative or a better method of doing this query?
$product = $db1q->query("
SELECT p.id, p.name, p.image, p.url,p.subcat as subcat, sc.id as scid,sc.name as scname
FROM Product as p
JOIN Product_Sub_Category as sc ON p.subcat = sc.id
WHERE p.visibility='1' AND find_in_set(p.id,'". $sidr['products'] ."')
ORDER BY FIELD(p.subcat,'4','5','6'), sc.sort_order ASC, p.sort_order ASC")
or die ('Unable to execute query. '. mysqli_error($db1q));
I just dumbed the query down to the basic level....
$product = $db1q->query("
SELECT id, name, image, url,subcat
FROM Product WHERE visibility='1' AND id IN ({$sidr['products']}) ORDER BY FIELD(subcat,'5','4','6','22')") or die ('Unable to execute query. '. mysqli_error($db1q));
and for some reason the order of my subcats are as follows....
3,12,23,5,5,4,4,4,4,4,22
Why wouldn't they begin with 5, 4, 6(doesn't exist), and 22? Then display 3,12, and 23 after those are first....
Simple Rextester Demo
When datatype is numeric don't compare to 'string' values
eg visibility = '1' if visibility is numeric you really shouldn't have the apostrophes around it. same in the field function given subcat.
$product = $db1q->query("SELECT id, name, image, url,subcat
FROM Product
WHERE visibility='1'
AND id IN ({$sidr['products']})
ORDER BY case when subcat in (5,4,6,22) then 0 else 1 end,
FIELD(subcat,5,4,6,22)
") or die ('Unable to execute query. '. mysqli_error($db1q));
or something like:
order by case when field(sort,'5','4','22') = 0 then (select max(sort)+1+sort from Product)
else field(sort,'5','4','22') end;
The issue with the 2nd approach is that it has to run a subquery for every record. In addition if the size of subcat/sort exceed or approach the max of int we'll run into a problem adding the values together. This problem is negated by using the 2 column sort approach in the first method.
Again, my gut feeling is that the first approach with 2 sort columns would be faster; and in my opinion easier to follow/maintain. The downfall is if the sort order defined changes then we have to change code. So... why have the order defined here... what isn't the order defined in a table; or is the order passed in as a parameter by user?
I currently have the following columns:
hit_id, visit_id, timestamp, page_url, page_next
hit_id increments upwards
visit_id is an ID of the visit and unique to each visitor
timestamp is a unix timestamp of the hit
page_url is the page being looked at
page_next is the page that was looked at next
I would like to to add a new column, page_last, where the previous page URL would go into - I should be able to extract this from page_url and page_next. I do not know why I did not create this column in the first place, probably a slight over-site really.
Is there anyway to fill this column using some MySQL trickery? page_last would always be empty on the initial hit on the website (doesn't contain referrer website).
I find the name page_last ambiguous (does it mean the previous page? or this last page on the visit?). I suggest you change it to page_prev.
The following comes close to filling this in, assuming that no one visited the same page multiple times in a visit:
select h.*, hprev.page_url as page_prev
from hits h left outer join
hits hprev
on hprev.page_next = h.page_url and hprev.visit_id = h.visit_id
If that is not true, then you need the most recent one. You can get that using a correlated subquery:
select h.*,
(select h2.page_url
from hits h2
where h2.visit_id = h.visit_id and h2.page_next = h.page_url and
h2.timestamp < h.timestamp
order by timestamp desc
limit 1
) as page_prev
from hits h
Doing the update is a bit tricky in MySQL, because you are not able to directly use the updated table in the update. But, the following trick should work:
update hits
set page_prev = (select page_url
from (select page_url
from hits h2
where h2.visit_id = hits.visit_id and
h2.page_next = hits.page_url and
h2.timestamp < hits.timestamp
order by timestamp desc
limit 1
) h3
)
The trick works because MySQL materializes views, so it actually creates a "temporary table" containing the necessary information for the update.
I have a little query, it goes like this:
It's slightly more complex than it looks, the only issue is using the output of one subquery as the parameter for an IN clause to generate another. It works to some degree - but it only provides the results from the first id in the "IN" clause. Oddly, if I manually insert the record ids "00003,00004,00005" it does give the proper results.
What I am seeking to do is get second level many to many relationship - basically tour_stops have items, which in turn have images. I am trying to get all the images from all the items to be in a JSON string as 'item_images'. As stated, it runs quickly, but only returns the images from the first related item.
SELECT DISTINCT
tour_stops.record_id,
(SELECT
GROUP_CONCAT( item.record_id ) AS in_item_ids
FROM tour_stop_item
LEFT OUTER JOIN item
ON item.record_id = tour_stop_item.item_id
WHERE tour_stop_item.tour_stops_id = tour_stops.record_id
GROUP BY tour_stops.record_id
) AS rel_items,
(SELECT
CONCAT('[ ',
GROUP_CONCAT(
CONCAT('{ \"record_id\" : \"',record_id,'\",
\"photo_credit\" : \"',photo_credit,'\" }')
)
,' ]')
FROM images
WHERE
images.attached_to IN(rel_items) AND
images.attached_table = 'item'
ORDER BY img_order ASC) AS item_images
FROM tour_stops
WHERE
tour_stops.attached_to_tour = $record_id
ORDER BY tour_stops.stop_order ASC
Both of these below answers I tried, but it did not help. The second example (placing the entire first subquery inside he "IN" statement) not only produced the same results I am already getting, but also increased query time exponentially.
EDIT: I replaced my IN statement with
IN(SELECT item_id FROM tour_stop_item WHERE tour_stops_id = tour_stops.record_id)
and it works, but it brutally slow now. Assuming I have everything indexed correctly, is this the best way to do it?
using group_concat in PHPMYADMIN will show the result as [BLOB - 3B]
GROUP_CONCAT in IN Subquery
Any insights are appreciated. Thanks
I am surprised that you can use rel_items in the subquery.
You might try:
concat(',', images.attached_to, ',') like concat('%,', rel_items, ',%') and
This may or may not be faster. The original version was fast presumably because there are no matches.
Or, you can try to change your in clause. Sometimes, these are poorly optimized:
exists (select 1
from tour_stop_item
where tour_stops_id = tour_stops.record_id and images.attached_to = item_id
)
And then be sure you have an index on tour_stop_item(tour_stops_id, item_id).
Im making a table generator as a school project.
In MySQL I have 3 tables namely process,operation,score. Everything looked fine until i tested out my "ADD column" button in the web app.
Previous saved data should be read properly but also include the new column in the format, problem is the previous data queried does not include any values for the new table, so I intended it to return a score of 0 if no records were found, tried IFNULL & COALESCE but nothing happens(maybe im just using it wrong)
process - processID, processName
operation - operationID, operationName
score - scoreID, score, processID, operationID, scoreType (score
types are SELF,GL,FINAL)
ps = (PreparedStatement)dbconn.prepareStatement("SELECT score FROM score WHERE processID=? and operationID=? and type=?ORDER BY processid");
here's a pic of a small sample http://i50.tinypic.com/2yv3rf9.jpg
The reason that IFNULL doesn't work is that it only has an effect on values. A result set with no rows has no values, so it does nothing.
First, it's probably better to do this on the client than on the server. But if you have to do it on the server, there's a couple of approaches I can think of.
Try this:
SELECT IFNULL(SUM(score), 0) AS score
FROM score
WHERE processID=? and operationID=? and type=?
ORDER BY processid
The SUM ensures that exactly one row will be returned.
If you need to return multiple rows when the table contains multiple matching rows then you can use this (omitting the ORDER BY for simplicity):
SELECT score
FROM score
WHERE processID = ? and operationID = ? and type = ?
UNION ALL
SELECT 0
FROM (SELECT 0) T1
WHERE NOT EXISTS
(
SELECT *
FROM score
WHERE processID = ? and operationID = ? and type = ?
)
I am having some trouble putting a query together. I need to show images pulled in the order of if they are in the "editorial" section then if they have an order to be displayed in it will show the editorial image first but if its not ordered in that section it would just default and pull the regular image that is ordered already (which may not be a editorial type image but is a preferred one if nothing else is available). What I have now is the query below BUT that doesn't pull the editorial ranked images first but rather the "ordered_by' seems to take precedence.
SELECT i.img_name, a.artist_path_name, a.artist_dir, a.artist_name, ck.catKey_id
FROM images AS i JOIN artists AS a USING (artist_id)
JOIN img_cat_table AS imc USING ( img_id )
JOIN catkeys AS ck USING (catKey_id)
WHERE site = 'editorial' AND editorial_order = 1 OR ordered_by = 1 GROUP BY artist_name ORDER BY ed_banner
Its probably something silly that I am missing -- any and all help is appreciated.
Try something like:
...
ORDER BY CASE WHEN site = 'editorial' AND editorial_order = 1 THEN 1 ELSE 2 END,
ed_banner
or the same idea in a simpler way
ORDER BY (site = 'editorial' AND editorial_order = 1) DESC, ed_banner
It simply utilizes the order of FALSE, TRUE.
You should remove the respective conditions from the WHERE clause.