Mysql select that matches all array elements [duplicate] - php

This question already has an answer here:
Select all rows that have at least a list of features
(1 answer)
Closed 9 years ago.
I have a mysql table
Table A
--------------------
item_id category_id
--------------------
1 1
1 2
1 4
2 1
2 3
Would like to make an sql query that will select all matches in an array
example:
given category_ids are 1,4 it should return only item_id 1
given category_ids are 1 it should return item_id 1 and 2
Thanks

For categories 1, 4:
SELECT item_id, COUNT(*) c
FROM TableA
WHERE category_id IN (1, 4)
GROUP BY item_id
HAVING c = 2
For category 1:
SELECT item_id, COUNT(*) c
FROM TableA
WHERE category_id IN (1)
GROUP BY item_id
HAVING c = 1
I think you should be able to see the pattern -- the HAVING clause should match the number of categories.
This assumes that item_id, category_id is unique in the table.

given category_ids are 1,4
SELECT item_id, category_id
FROM TableA
WHERE category_id IN (1, 4)
given category_ids are 1
SELECT item_id, category_id
FROM TableA
WHERE category_id IN (1)

Related

Projecting mySQL database, how to deal with multiple categories

I need a help with projecting my database. The purpose of this database will be to show offers in different categories. There are 1-6 categories to each item. There are around 80 categories types, so I decided to make three tables as below:
table1:
ID Item_id
1 1
2 2
3 3
4 4
5 5
table2:
ID Item_id Category
1 1 cat55
2 1 cat56
3 1 cat57
4 1 cat58
5 2 cat42
6 2 cat43
7 2 cat44
8 2 cat45
9 3 cat42
etc.
table3:
Category_id category_name
cat55 apples
cat56 oranges
cat57 bananas
cat58 pineapples
Am I doing this right? I've got a problem to make proper sql query to show my categories in php, because when I use this query:
SELECT table1.*, table2.*, table3.*
FROM table1
INNER JOIN table2
ON table1.item_id = table2.item_id
INNER JOIN table3
ON table2.category=table3.category_id
It only gives me the first category name, when I need all of them and show them like this:
Item 1: apples, oranges, bananas, pineapples
Item 2: cat42, cat43, cat44, cat45
Item 3: cat42
What am I doing wrong? Is it wrong query or I need to change the database structure to like this
table 1 and 3 unchanged
table 2:
ID Item_id c1 c2 c3 c4 c5 c6
1 1 cat55 cat56 cat57 cat58 null null
2 2 cat42 cat43 cat44 cat45 null null
3 3 cat42 null null null null null
I'm using foreach loop, so I can do only one query, I know that more queries are possible, but I need to make it as simple as possible.
If you want to fetch all names in single row for each item, following query will work:
SELECT table1.Item_Id,Group_Concat(t3.category_name separator ',') as Category_Name
FROM table1
INNER JOIN table2
ON table1.item_id = table2.item_id
INNER JOIN table3
ON table2.category=table3.category_id
Group by table1.Item_Id;
I don't find any problem in your DB Structure.
Hope it helps!

PHP MySQL Group BY Having issue

Suppose I have a table like:
ID|Word |Reference
1 |Dog |1
1 |Fish |2
1 |Sheep|3
2 |Dog |4
2 |Fish |5
3 |Sheep|6
4 |Dog |7
I want to select all ID's that have the word Dog AND Sheep. So the result should be ID's: 1 and 2. I tried using this query:
SELECT ID FROM `Table` WHERE Word='Dog' OR Word='Fish' GROUP BY ID Having Word='Dog AND Word='Fish'
However, this AND in the Having clause makes me get 0 results. So, am I doing something wrong or is there another way to achieve wat I want based on MySQL query only (to optimize speed, since it has to search through many rows with the same setup as in the example above)
Basically the problem is the AND statement over multiple rows with the same ID.
UPDATE:
I need to get the reference for the ID's that where found. E.g. when the ID 1 and 2 are returned I need to know that ID 1 has reference 1 and 2. ID 2 has reference 3 and 4. Currently, I'm using this query:
SELECT ID FROM `Test` WHERE Word in ('Dog', 'Fish') GROUP BY ID HAVING count(DISTINCT Word) = 2;
Thanks
Here are two solutions that return the correct records, the first as individual records by ID and Reference, and the second with one record per ID and the Words and References as comma separated in columns.
Setup table and populate rows:
DROP TABLE IF EXISTS `list1`;
CREATE table `list1` (
id int(10),
Word varchar(10),
Reference int(10)
);
INSERT INTO `list1` (`ID`, `Word`, `Reference`)
VALUES
(1, 'Dog',1),
(1 ,'Fish',2),
(1 ,'Sheep',3),
(2 ,'Dog',4),
(2 ,'Sheep',5),
(3 ,'Sheep',6),
(4 ,'Dog',7);
Returns one row for each combination of ID and Word
SELECT
t.`ID`,
t.`Word`,
t.`Reference`
FROM `list1` as t
JOIN (
SELECT
t1.`ID` as `ref_id`
FROM `list1` AS t1
WHERE `Word` in ('Sheep','Dog')
GROUP BY t1.`ID`
HAVING count(DISTINCT t1.`Word`) = 2
) AS ts
ON t.`ID` = ts.`ref_id`
WHERE t.`Word` in ('Sheep','Dog')
ORDER BY t.`ID`,t.`Word`;
Results
ID | Word | Reference
1 | Dog | 1
1 | Sheep | 3
2 | Dog | 4
2 | Sheep | 5
Returns one row per ID, with a comma separated list of Words in one column, and a comma separated list of Reference in another.
SELECT
t.`ID`,
GROUP_CONCAT(t.`Word`) AS `Words`,
GROUP_CONCAT(t.`Reference`) AS `References`
FROM `list1` as t
JOIN (
SELECT
t1.`ID` as `ref_id`
FROM `list1` AS t1
WHERE `Word` in ('Sheep','Dog')
GROUP BY t1.`ID`
HAVING count(DISTINCT t1.`Word`) = 2
) AS ts
ON t.`ID` = ts.`ref_id`
WHERE t.`Word` in ('Sheep','Dog')
GROUP BY t.`ID`
ORDER BY t.`ID`,t.`Word`;
Results:
ID | Words | References
1 | Dog,Sheep | 1,3
2 | Dog,Sheep | 4,5
You need to join the table on itself. This way you can pick up where the id's are the same for instances where dog and sheep overlap.
Try this:
declare #t table (id int , Word varchar(10) )
insert into #t (ID, Word) values (1, 'Dog'),
(1 ,'Fish'),
(1 ,'Sheep'),
(2 ,'Dog'),
(2 ,'Sheep'),
(3 ,'Sheep'),
(4 ,'Dog')
select t.ID
from #t as t
join #t as t1 on t1.id = t.id
where t.word = 'Dog' and t1.word = 'Sheep'
Here's one way to do it by joining your table to itself.
SELECT t1.id FROM `Table` t1
INNER JOIN `Table` t2 ON t1.id = t2.id
WHERE t1.word='Dog' AND t2.word='Sheep';
The answer for my problem is solved using underneath query:
SELECT ID, GROUP_CONCAT(Reference) as ReferencesGrouped FROM `Test` WHERE Word in ('Dog', 'Fish') GROUP BY ID HAVING count(DISTINCT Word) = 2;
This will return me:
ID|ReferencesGrouped
1 |1,4
2 |4,5

Mysql Query Join two table Order by one table column

I have two table (table 1 and table 2) . I want to show all the rows from table1 by joining with table2 which have multiple rows with same table1 id (foreign key relation) and will sort the result by table2 priority column (order by desc).
Table1
Table2
Result will be
thanks in advance
Edit
Table1
id name
1 test1
2 test2
3 test5
4 test7
5 test9
6 test3
Table2
id table1_id event priority
1 2 abc 0
2 2 kbc 0
3 2 abc 2
4 2 kbc 1
5 4 fgg 2
6 4 dss 3
7 1 fgfg 2
8 5 fgfg 2
9 6 xcxc 1
10 6 fgfh 3
Result
id_table1 name event priority
4 test7 dss 3
6 test3 fgfh 3
2 test2 abc 2
1 test1 fgfg 2
5 test9 fgfg 2
3 test5 NULL NULL
In the question you mentioned you need to select the data where id from table1 is available more than once in the table2 which does not match with the result set you gave.
Considering the original requirement the following should do the trick
select
t2.table1_id as id_table1,
t1.name,
t2.priority,
t2.event
from table1 t1
join
(
select
p1.table1_id,
p1.event,
p2.priority
from table2 p1
join(
select
max(priority) as priority,
table1_id
from table2
group by table1_id having count(*) > 1
)p2
on p2.table1_id = p1.table1_id and p2.priority = p1.priority
)t2
on t1.id = t2.t1id
order by t2.priority desc
Here is a demo
The result will get the same event corresponding the max priority column
This will get the result set that you want. You mentioned that you only need the items table1 ids that reflects more than once but result query shows tableid1 "1" even though it is only present once:
SELECT DISTINCT t1.id,t1.name ,t2.event, t2.priority
FROM TABLE2 t2
right join
TABLE1 t1
on t1.id=t2.table1_id
order by t2.priority desc
Try this query:
SELECT t1.*,t2.priority FROM table1 t1
INNER JOIN table2 t2
ON t1.id=t2.id
ORDER BY t2.priority DESC
Primary key and foreign key should have the same name. The syntax should be
SELECT Table1.id_table1,Table1.name,Table2.event,Table.priority FROM
Table1 LEFT JOIN Table2 ON
Table1.id=Table2.id
ORDER BY Table2.priority DESC
Make the following changes in Table2:
Get rid of the first column or rename it
Rename second column(your foreign key) to "id".

left join issue with mysql

I have two tables and trying to join both of them based on primary and foreign key.But the problem is that in second table the foreign key has multiple duplicate rows.
Structure :-
1 Table - category
catid catname
1 AAA
2 BBB
3 CCC
2 Table - answers
ansid catid userid
1 1 9
2 1 9
3 2 9
4 2 6
The result should be
userid catid catname present in answers table
null 1 AAA no
6 2 BBB yes
null 3 CCC no
My query is
SELECT a.userid, c.catid,c.catname,
case when sum(a.catid is not null) > 0
then 'yes' else 'no' end as present_in_answers_table
from answers a left join
category c on c.catid = a.catid
where (a.userid = 6) group by c.catid
But it is not returning the results what I want.It returns only one row that is
userid catid catname present in answers table
6 2 BBB yes
I think you need to switch the order of the joins, so you keep everything in the category table and then move the where condition to the on clause:
SELECT a.userid, c.catid, c.catname,
(case when count(a.catid) > 0 then 'yes' else 'no'
end) as present_in_answers_table
from category c left join
answers a
on c.catid = a.catid and
a.userid = 6
group by c.catid;
Note that I also changed the sum() to a count() -- count() automatically counts the number of times the argument is not NULL.

Fetch data from mapping table if the condition matches in multiple rows

product_id property_id
1 2
1 5
2 2
3 5
I have a mapping table as above. I want to get only product with id =1 if product_id in (2,5). i.e. I want to fetch data if the table contains both 2,5 not the data if it is with property_id only 2 or 5
select group_concat(distinct product_id) product_ids from table where property_id in (2,5)
UPDATE:
The property_id in can be property_id in(2,5,....). I get output from form as 2,5,.... and so on. Its not just for the single case. I just want the output if the condition in property_id in matches the whole series.
This how it could be done
select
product_id from
table_name
where property_id in (2,5)
group by product_id
having count(*) = 2
All you need to change having count(*) = 2 to the number of items inside IN() , right now its 2 and if you are looking at 3 property id then it will be 3 and so on.
select distinct a.product_id
from table a, table b
where a.product_id = b.product_id
and a.property_id = 2
and b.property_id = 5

Categories