Answer the question
In order to leave comments, you need to log in
How to write an SQL query to select an element by its characteristics?
I suffer the second day, suggest pzh.
The essence of the task:
I need to pull out a row from the page table , knowing only iCityID , while there can be several iCityID values.
Examples:
Example 1: I have values iCityID = 101 and 102. The output should be the First page . At the same time, 101 also belongs to the Gateway , but you don’t need to pull it out, since there is no exact match.
Example 2: I have values iCityID = 101. At the output, you need to get the Second page . At the same time, 101 also belongs to the First Page, but you don't need to pull it out, since it also has another iCityID (102).
DB structure:
Table: page
| Table: city
| Link table: page_city
|
Answer the question
In order to leave comments, you need to log in
If the pair (iPageID, iCityID) is unique, then
SELECT *
FROM (
SELECT `iPageID`
FROM `page_city`
WHERE `iCityID` IN (101, 102)
GROUP BY `iPageID`
HAVING COUNT(*) = 2
) AS `t1`
JOIN (
SELECT `iPageID`
FROM `page_city`
GROUP BY `iPageID`
HAVING COUNT(*) = 2
) AS `t2` USING (`iPageID`)
Put LIMIT 1
at the end of the request for a selection from 'page_city' .
And in the request itself, depending on which page is needed, the first or second, put ORDER.
for example
If I understand the problem correctly...
SELECT page_city.iPageID,
COUNT(page_city.iCityID)
FROM (
SELECT iPageID,
COUNT(iCityID) cnt
FROM page_city
GROUP BY iPageID
) cnt_page,
page_city
WHERE cnt_page.iPageID = page_city.iPageID
AND page_city.iCityID IN (:LIST)
GROUP BY iPageID
HAVING COUNT(iCityID) = cnt_page.cnt;
There is not enough information about the task itself.
Try this:
DECLARE id1 int, id2 int
Example 1
SET id1 = 101
SET id2 = 102
Example 2
SET id1 = 101
SET id2 = 101
SELECT case when id1 <> id2 then min(iPageID) else max(iPageID) end
FROM page_city
WHERE iCityID IN(@Id1,@Id2)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question