I
I
Ilya Solovyov2015-10-14 17:31:33
PHP
Ilya Solovyov, 2015-10-14 17:31:33

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
iPageIDsPageName
oneFirst page
2Second page
3Third page

Table: city
iCityIDsCityName
101Moscow
102St. Petersburg
103Kazan
104Yaroslavl
105Vladivostok

Link table: page_city
iPageIDiCityID
one101
one102
2101
3103
3105

Answer the question

In order to leave comments, you need to log in

4 answer(s)
R
Rsa97, 2015-10-14
@ilya_solovyv

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`)

(Corrected, at first I did not notice the second condition).

G
Georgy Vizov, 2015-10-14
@goshaviz

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...

F
faustxp, 2015-10-14
@faustxp

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;

Although the problem of the first request will not solve

S
StrannikF, 2015-10-14
@StrannikF

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 question

Ask a Question

731 491 924 answers to any question