cross referencing tables and inserting the results into another table SQL - php

So i have 3 tables that are like the following:
table 1 - cats - that has the following structure:
id name plural_name
0 painters painters
1 builders builders
table 2 - places - that has the following structure
place_id place_name classification
243 painter comp painters
230 builder comp builders
table 3 - rel_place_cat - that has the following structure
id place_id cat_id
0 243 0
1 230 1
So basically i need to run an SQL command to find to find the category id number in table 1 and the place_id from table 2 and insert the data into table 3
can this be done ?
Thank you

If you want to make that insert also repeatable?
Then you could also join to the relation table.
And only insert the missing relations.
Example query:
INSERT INTO rel_place_cat (place_id, cat_id)
SELECT p.place_id, c.id
FROM cats c
JOIN places p ON p.classification = c.plural_name
LEFT JOIN rel_place_cat r ON (r.place_id = p.place_id AND r.cat_id = c.id)
WHERE r.id IS NULL
GROUP BY p.place_id, c.id;
Not sure if joining the "classification" to "plural_name" or to "name" would be better.
In the sample they are the same anyway.
But those values in "classification" are all plural, so "plural_name" was used for the join.

Something like:
insert into table3(place_id, cat_id)
select place_id, cat_id
from(select place_id, cat_id
from table1
inner join table2 on table1.name = table 2.classification)
Should work.

Related

MySQL WHERE filter based on subquery in SELECT

I have a table named Records that shows products. I also have a table named Categories that shows the categories for each individual product (if one exists).
The Categories table is structured liked:
id category_id
-- -----------
1 1
1 3
3 1
3 2
5 4
The query I run to pull record ID and category ID(s) is:
SELECT
Records.id,
(SELECT
GROUP_CONCAT(C.category_id)
FROM `Categories` C
WHERE Records.id = C.id) AS 'CategoryName'
FROM
Records
The output will return:
id CategoryName
-- ------------
1 1,3
2 NULL
3 1,2
4 4
5 NULL
I have an area of my website where users can filter records by category. Let's say user wants to filter for category = 1 or 2. I was thinking I just tack on a WHERE FIND_IN_SET(1,CategoryName) OR FIND_IN_SET(2,CategoryName) but this does not work because of the MySQL execution order and CategoryName column does not exist yet.
What is the best way to filter for category_id? The input for categories will be comma separated but I can use PHP to explode() the string to separate them.
You can rewrite the query with a LEFT join of Records to Categories:
SELECT r.id,
GROUP_CONCAT(c.category_id) AS CategoryName
FROM Records r LEFT JOIN Categories c
ON c.id = r.id
GROUP BY r.id
and if you want to use the same query for filtering all you have to do is add at the end a HAVING clause:
HAVING FIND_IN_SET(1, CategoryName) OR FIND_IN_SET(2, CategoryName)
Or, you can filter first and then aggregate:
SELECT r.id,
GROUP_CONCAT(c.category_id) AS CategoryName
FROM Records r INNER JOIN Categories c
ON c.id = r.id
WHERE c.category_id IN (1, 2)
GROUP BY r.id

mysql fetch data from two tables

Please find picture to get more clarification on what I am asking
Click here
Let me tell you full description
I have two tables -
Table1 contains book_id and book_name
second table -
Table2 contains book_id, stock and cs_id
I want when someone choose cs_id so result displayed in terms of book_name and not book_id
I'm sorry for short description...
I have two tables in mysql database -
table1
SN ID Name
1 E-11 ELC
2 E-13 ELX
3 D-41 DME
and table2
SN ID CS_ID
1 E-11 C01
2 E-13 C01
3 D-41 C54
How to get result of all name from table1 using one cs_id from table2 using php.
Please help.
Thanks in advance!
Here what I'm using
$query = "SELECT table1.id, table2.name FROM table1 INNER JOIN table2 ON table1.id = table2.id WHERE table1.cs_id=$cs_id'
this is showing me 0 result.
Use TABLE LEFT JOIN
LIKE
select tb1.name,tb2.ID FROM TABLE1 as tb1 LEFT JOIN TABLE2 as tb2 ON tb1.ID=tb2.ID where tb2.CS_ID='$request_id';
I hope its work

tricky mysql query with categories

here's my data structure:
category_main
id name
---------------------
1 catmain1
2 catmain2
category_sub
id name id_catmain
---------------------
1 catsub1 1
2 catsub2 1
3 catsub3 2
images
id name catsub
---------------------
1 image1 1
2 image2 1
3 image3 2
4 image4 3
desired output:
id_catmain catmain images_total
--------------------------------------------------
1 catmain1 3
2 catmain2 1
the problem is getting the total amount of images per main category ..
i tried something like (as a view)
select categories.*, group_concat(id) as all_cat from categories group by id_catmain
then querying that view using FIND_IN_SET .. but i think there must be a better way using one query only. any ideas?
thanks
Something along these lines should work I think:
SELECT c.id, c.name, COUNT(*) AS images_total FROM images i
JOIN category_sub cs ON cs.id = i.catsub
JOIN category_main c ON c.id = cs.id_catmain
GROUP BY c.id
What you are basically doing there is tying all the image table's rows to the subcategories they represent, then tying the main categories to the same row through the subcategory id. Then you can simply count all the rows, grouping the amount of counted rows by all the different main category ids.
You can solve this in many ways. One of these would be to use a subquery:
SELECT c.id AS id_catmain, c.name AS catmain,
(SELECT COUNT(i.id) AS totalImages
FROM images i
INNER JOIN category_sub s ON i.catsub = s.id
WHERE s.id_catmain = c.id) as totalImages
FROM category_main c
ORDER BY c.name ASC;
Sample here: http://sqlfiddle.com/#!9/d78e2/5
This is not better than Bun's answer, it's just to say there are other ways of doing this.

SQL: Get null as a return value for rows that don't match query

I have a table, Entity and a table Friends. I want to get the names of people who have visited the same location, but I only want to return them if they are not friends with the person (suggested friend query). In order to do this I have written the following query:
SELECT Entity_Id,
Category AS FC
FROM entity
LEFT
JOIN friends
ON entity.Entity_Id = friends.Entity_Id1
OR entity.Entity_Id = friends.Entity_Id2
WHERE Entity_Id IN ( :list_of_ids )
AND Entity_Id != :user_id
AND Category != 4
GROUP
BY Entity_Id
:list_of_ids is a comma separated list of user id's and in my test query there are 82 users, however only 15 users are returned from the query, where the users returned are users who have a relationship with :user_id.
Any user who does not have a relationship in the table is not returned in the query. I thought by providing a LEFT OUTER JOIN it would return NULL for fields that were not found in the friends table.
----- EXPECTED -----
--------------------
Entity_Id FC
--------------------
1 3
2 2
3 2
4 null
52 null
64 null
------ ACTUAL -------
---------------------
Entity_Id FC
---------------------
1 3
2 2
3 2
The structure of my friends table is as follows, also note that it supports reciprocal relationships if that is any help...
------ FRIENDS ------
---------------------
fid PK
entity_id1 INT
entity_id2 INT
category INT -- 1 = Facebook, 2 = G+, 3 = App, 4 = Blocked
How can I return the users who have a missing relationship?
You want a left outer join. But, with a left join, the conditions on the second table need to go into the on clause:
SELECT e.Entity_Id, f.Category AS FC
FROM entity e LEFT JOIN
friends f
ON e.Entity_Id IN (f.Entity_Id1, f.Entity_Id2) AND
f.category <> 4
WHERE e.Entity_Id IN ( :list_of_ids ) AND
e.Entity_Id <> :user_id
GROUP BY e.Entity_Id;
When you have the condition on category in the WHERE clause, you turn the LEFT JOIN into an INNER JOIN. When there is no match, category has a value of NULL, which fails the comparison.
Which table does the Category belong to? If its a friends column, move Category != 4 from WHERE to ON to get true outer join. (Otherwise it executes as a regular innner join...):
SELECT Entity_Id, Category AS FC
FROM entity
LEFT JOIN friends
ON (entity.Entity_Id = friends.Entity_Id1
OR entity.Entity_Id = friends.Entity_Id2)
AND Category != 4
WHERE entity.Entity_Id IN ( :list_of_ids )
AND entity.Entity_Id != :user_id
GROUP
BY Entity_Id

Avoid duplicating data in php

I have two mysql tables called room_type and resve_room.
The room_type table has room numbers 5, 3, 6 ,9 ,10. The resve_room table has room numbers 3 and 9.
How can I write an SQL query that filters out reserved room number 3 and 9 from the room_type table. I want to return the following room numbers 5,6,10.
I have tried using the following SQL but it only returned 3 and 9 :
SELECT room_type.room_no
FROM room_type,in_hand_room
WHERE in_hand_room.room_no=room_type.room_no
&& room_type.room_id='$room_id
Try something like this
SELECT B.Accountid
FROM TableB AS B
LEFT
JOIN TableA AS A
ON A.ID = B.Accountid
AND A.ID IS NULL;
Or maybe this
select ids from TableB EXCEPT select id from TableA
Try the follwoing
SELECT room_type.room_no
FROM room_type
WHERE room_type.room_no NOT IN (SELECT resve_room.room_no from resve_room )
or in_hand_room instead of resve_room beacuse it 's not clear from your desc which one is your reservation table

Categories