MySql query on 3 different tables - mysql

I have 3 tables.
Owners:
ownerID name
1 josh
Pets:
petID name
1 M
2 x
3 f
4 h
PetsOwners:
petID ownerID
1 1
3 1
4 1
I have a query that returns the ownerID from a person. "SELECT ownerID FROM Owners WHERE name = 'josh';" This will return ownerID = 1. I need a query that returns all pets that josh owns. In this case will be "m", "f" and "h" according to the petsOwners table.

If you have ownerId use
SELECT p.name
FROM Pets p
JOIN PetsOwners po
ON p.petID = po.petID
WHERE po.ownerID = 1
If you only have the owner name, need join all 3 tables
SELECT p.name
FROM Pets p
JOIN PetsOwners po
ON p.petID = po.petID
JOIN Owners o
ON po.ownerID = o.ownerID
WHERE o.name = 'josh'

If you just want their names:
SELECT Pets.name
FROM Pets, PetsOwners, Owners
WHERE Pets.petID = PetsOwners.petID
AND Owners.ownerID = PetsOwners.ownerID;

try this:
select a.ownerID,a.`name`as OwnerName, b.petID,b.`name` as PetName from
(select ownerID `name` from Owners) as a
right join
(select a.petID,a.`name`,OwnerID from
(select petID,`name` from Pets) as a
left JOIN
(select petID,OwnerID from PetsOwners) as b
on a.petID = b.petID) as b
on a.ownerID = b.OwnerID

I see your question and this is easy you see the query I wrote blow:
SELECT links.`link`,
links.`link_id`
FROM links
WHERE links.`link_id` NOT IN
(SELECT Y.`link_id`
FROM users X
INNER JOIN user_visited Y ON X.`user_id` = Y.`user_id`
WHERE X.`user_id` = 22 );

Related

SQL Query: Joining 4 tables to one

I tried all the similar questions but I can not get what I want.
Need help with Joining the table.
1. Table bookings:
id = 1 customer_id = 1 booking_details = 'venue etc'
2. Table customers:
id = 1 name = 'John Citizen'
3. Table: booking_objects:
id = 1 booking_id = 1 object_id = 1
id = 2 booking_id = 1 object_id = 2
4. Table objects:
id = 1 name = 'Object 1'
id = 2 name = 'Object 2'
I want to join tables to I get "Venue etc, Jhon Citizen, Oject 1, Object 2"
currently I am getting "Venue etc, Jhon Citizen" using below query
$this->db->select("bookings.bookig_details, customers.name as customer_name, objects.name as object_name")->join("customers", "customers.id = bookings.customer_id", "left outer")
In your requirement, Venue etc, Jhon Citizen, Object 1, Object 2 are mentioned. Object 1 and Object 2 comes under same column i.e, objects.name.
As per my understanding you need booking_details, customer_name, obj_name are your required columns.
select b.booking_details, c.name as customer_name, o.name as obj_name
bookings b
inner join
customers c
on b.customer_id = c.id
inner join
booking_objects bo
on b.id = bo.id
inner join
objects o
on bo.object_id = o.id
You can change the join types based on your requirement.
Instead of using values of the required output, it would have been better to use required columns in your question for clarity.
You need to use Self JOIN
like this.
select b.booking_details,c.name 'customer_name',o1.name 'o1Name',o2.name 'o2Name'
FROM objects o1
join objects o2 ON o1.id = 1 and o2.id = 2
join booking_objects bo on o1.id = bo.object_id
join bookings b on b.customer_id = bo.booking_id
join customers c on bo.booking_id = c.ID
sqlfiddle:http://sqlfiddle.com/#!9/594973/14

MySQL Select Distinct with Left Join?

I am trying to get a list of company_id's that have no company-level notes. The company may, however, have location-level notes.
company
-------------------------
company_id name deleted
1 Foo 0
2 Bar 0
3 Baz 0
location
-----------------------
location_id company_id
6 1
7 2
8 3
note
-----------------------------------------
note_id company_id location_id deleted
10 2 6 0 // location-level note
11 1 7 0 // location-level note
12 null 8 0 // location-level note
13 2 null 0 // company-level note
I would want my result table to be this:
company_id name
1 Foo
3 Baz
Update
Foo/company_id = 1 does not have a company-level note because the note also has a location_id, which makes it a location-level note. Company-level notes are notes that only link to a company (and not a location).
End of Update
I've tried doing something like this, but it returns an empty set, so I'm not sure if it's working and there aren't any companies without company-level notes or if I'm doing something wrong.
SELECT DISTINCT
c.company_id,
c.name
FROM company AS c
LEFT JOIN note AS n
ON c.company_id = n.company_id
WHERE
c.deleted = 0 AND
n.deleted = 0 AND
n.location_id IS NOT NULL AND
n.location_id != 0 AND
c.company_id = (SELECT MAX(company_id) FROM company)
Revised Accepted Answer by Mike
SELECT
company_id,
name
FROM company
WHERE
deleted = 0 AND
company_id NOT IN (
SELECT DISTINCT
c.company_id
FROM company AS c
INNER JOIN note AS n
ON c.company_id = n.company_id
WHERE (
n.deleted = 0 AND
(n.location_id IS NULL OR
n.location_id = 0)
)
);
The easiest way to think about this is to first find the all the companies that have company level notes, which you can do with
select distinct c.company_id
from company c
inner join notes n
on c.company_id = n.company_id
where n.location_id is null;
Then simply remove these companies from the company select:
select company_id,
name
from company
where company_id not in (select distinct c.company_id
from company c
inner join notes n
on c.company_id = n.company_id
where n.location_id is null);
*Updated to use inner join instead of comma-separated join.
SELECT DISTINCT c.*
FROM company c
LEFT
JOIN note n
ON n.company_id = c.company_id
AND n.location_id IS NULL
WHERE n.note_id IS NULL;

MySql count result from another table not return correct number

In my query i want to count how much user have photos and how much have pets. When i count how much pets he have that work good. When i try to count how much photos have than not work. He return me wrong result.
Full query is :
SELECT
acc.account_id,
CONCAT(acc.account_firstname,' ', acc.account_lastname) AS full_name,
acc.account_username AS username,
acc.account_website_url AS website,
g.gender_name AS gender,
acc.account_birthday AS birthday,
acc_t.account_type_name AS account_group,
(SELECT COUNT(*) FROM pb_account_photos WHERE owner_id = acc.account_id) AS photoCount,
(SELECT COUNT(*) FROM pb_account_photo_albums WHERE album_account_id = acc.account_id) AS photoAlbumCount,
CONCAT(country.country_name,'/',city.city_name) AS location,
COUNT(p.pet_id) AS petCount,
(SELECT CONCAT(s.value, '/uploads/user_data/',acc.account_id,'/photos/',photo.photo_guid, '/',.photo.photo_name) FROM pb_settings AS s WHERE s.key = 'siteurl') AS profile_picture,
(SELECT CONCAT(s.value, '/uploads/user_data/',acc.account_id,'/photos/',cover.photo_guid, '/',.cover.photo_name) FROM pb_settings AS s WHERE s.key = 'siteurl') AS cover_picture
FROM pb_accounts AS acc
LEFT JOIN pb_account_genders AS g ON g.gender_id = acc.account_gender_id
LEFT JOIN pb_animal_pets AS p ON p.pet_owner_id = acc.account_id
LEFT JOIN pb_account_types AS acc_t ON acc_t.account_type_id = acc.account_type_id
LEFT JOIN pb_locations AS loc ON loc.location_id = acc.account_location_id
LEFT JOIN pb_country AS country ON country.country_id = loc.location_id
LEFT JOIN pb_city AS city ON city.city_id = loc.city_id
LEFT JOIN pb_account_photos AS photo ON photo.photo_id = acc.profile_picture_id
LEFT JOIN pb_account_photos AS cover ON cover.photo_id = acc.profile_cover_picture_id
WHERE acc.account_id = 1 GROUP BY acc.account_id
Output
account_id full_name username website gender birthday account_group photoCount location petCount profile_picture cover_picture
---------- ---------------- -------- -------------- ------ ---------- ------------- ---------- -------------- -------- --------------------------------------------------------------------------------------------------------------------------- -----------------------------------------------------------------------------------------------------------------------------
1 Jon Doe jondoe013 www.google.com Male 2016-01-07 Administrator 2 Serbia/Belgrade 2 http://work.example.com/uploads/user_data/1/photos/9A5EF85E-F691-F42E-C20C-BCDC765BFA1B/6c28b264470e7a7f2829ea5b7290cbba.jpg http://work.example.com/uploads/user_data/1/photos/14B6D588-68E6-6783-324B-673CBCCD4FBC/6db0935929d08f7c51ded014bd9e73df.jpg
Problem:
Query return photoCount just 2 but i have 123 pictures. I also try to Group by for photo_id but not working.
Also in this case i use subquery and also try to remove subquery for photoCount and put COUNT(photo.*) AS photoCount and result is the same

getting count on same column using inner join

I have a table like this, in which I need to set the male and female counts for the primary key id:
summaryTable:
id femaleCount maleCount
-----------------------------
s1 ? ?
s2 ? ?
... and so on
There is a detail table as below, that has the users corresponding to each id of summaryTable:
id parentId userId
--------------------------
1 s1 u1
2 s1 u2
3 s2 u2
4 s2 u2
...and so on
The third is the user table like this:
userTable:
userId gender
-------------
u1 M
u2 F
u3 F
..and so on
I have to update the summary table with the counts of male and female. So as per the above, for id=s1, femaleCount should be set to 1 , maleCOunt=1
For id=s2, femaleCOunt should get set to 2 and maleCount=0
Is this possible to do using an UPDATE query in MySQL?
I tried the following, but this returns the sum of occurences of a user i.e. if u1 occurs 2 times for p1(say), then it will return count as 2 and not 1:
SELECT
d.parentId,
SUM(gender = 'F') AS 'F#',
sum(gender = 'M') as 'M#'
FROM detailsTable as d
JOIN userTable as c on c.userId = d.userId
GROUP BY d.parentId;
Also tried as below, but it gave an error:
select d.parentId,
count(case when c.gender='M' then 1 end) as male_cnt,
count(case when c.gender='F' then 1 end) as female_cnt,
from detailsTable d, userTable c where d.userId=c.userId group by d.parentId, d.userId ;
Further, my problem doesnt just end at the select, I need to get the values and then update these in the summary table too.
I might be rusty on the syntax for MySql but I believe this does what you need. The CASE/SUM is effectively a pivot to get the counts, then you can update the table as normal.
UPDATE summaryTable AS st
INNER JOIN ( SELECT parentId
,SUM(CASE WHEN gender = 'f' THEN 1
ELSE 0
END) femaleCount
,SUM(CASE WHEN gender = 'm' THEN 1
ELSE 0
END) maleCount
FROM userTable d
INNER JOIN (SELECT DISTINCT parentId, userId FROM detail) ut ON d.userId = ut.userId
GROUP BY parentId
) AS c ON c.parentId = st.parentId
SET femaleCount = c.femaleCount
,maleCount = c.maleCount

MYSQL - Union SELECT & GROUP BY Not working

I have 3 table, log, member, also guest, but my log i stored as customer(user)'s id only, which is either their guest_id or member_id. So here's the problem, because they're from different table, I'm not sure how to join & group together their data.
checkout_log table
id user_id checkout_as
--------------------------------------
1 1 member
2 2 guest
members table
id fullname
--------------------------------------
1 member01
2 member02
guests table
id fullname
--------------------------------------
1 guest01
2 guest02
What I wanted to Achieve - Result
id user_id fullname checkout_as
----------------------------------------------
1 1 member01 member
2 2 guest02 guest
Had tried following sql statement with UNION ALL, or GROUP BY , but had no luck.
SELECT * FROM
(
SELECT checkout_log.id,checkout_log.user_id,guests.fullname,guests.email,checkout_log.checkout_as
FROM checkout_log
LEFT JOIN checkout_product ON checkout_product.checkout_log_id = checkout_log.id
LEFT JOIN guests ON checkout_log.user_id = guests.id
UNION ALL
SELECT checkout_log.id,checkout_log.user_id,members.fullname,members.email,checkout_log.checkout_as
FROM checkout_log
LEFT JOIN checkout_product ON checkout_product.checkout_log_id = checkout_log.id
LEFT JOIN members ON checkout_log.user_id = members.id
) derivedTable
GROUP BY id
Try doing this with joins instead of union
select cl.id, cl.user_id,
coalesce(m.fullname, g.fullname) as fullname,
cl.checkout_as
from checkout_log cl left join
members m
on cl.user_id = m.id and cl.checkout_as = 'member' left join
guests g
on cl.user_id = g.id and cl.checkout_as = 'guest';