join and null values rows not showing - php

I have this statement:
SELECT personen.*, klassen.naam as klas FROM `personen`
JOIN `klassen` ON `klassen`.id = `personen`.Id
WHERE `rol` = "Docent" ORDER BY id
I know that it basically puts the column klassen.naam into personen by checking if the foreign key K_Id is the same as the id of Klassen:
In the table above I have 4 results, these are all the people who have a K_Id assigned, however there are 2 more people who have a K_Id of null:
My problem is that when K_Id is null it doesn't return anything at all, which makes sense, I just don't know how to fix it.
My question is: How can i write the statement so that it still shows all the other rows where the K_Id value is null?

SELECT personen.*, klassen.naam as klas
FROM `personen`
JOIN `klassen`
ON `klassen`.id = `personen`.Id
WHERE `rol` = "Docent"
ORDER BY id
You should use left join if you want all of your data from personen Table where personen.id is not present in klassen table it look like this
SELECT personen.*, klassen.naam as klas
FROM `personen`
LEFT JOIN `klassen`
ON `klassen`.id = `personen`.Id
WHERE `rol` = "Docent"
ORDER BY id

You would use a left join for this purpose. Assuming rol is in the personen table:
SELECT p.*, k.naam as klas
FROM `personen` p LEFT JOIN
`klassen` i
ON i.id = p.Id
WHERE p.`rol` = 'Docent'
ORDER BY p.id;
If rol is in the klassen table, then:
SELECT p.*, k.naam as klas
FROM `personen` p LEFT JOIN
`klassen` i
ON i.id = p.Id AND i.`rol` = 'Docent'
ORDER BY p.id;
Note that I also introduced table aliases in the query. These make queries easier to write and to read.
Also, this will return all rows in the personen table (subject to the where), including non-matches. If you just specifically wanted NULL values, then you would use:
SELECT p.*, k.naam as klas
FROM `personen` p JOIN
`klassen` i
ON i.id = p.Id or p.id is null
WHERE p.`rol` = 'Docent'
ORDER BY p.id;
I'm guessing you really want the left join version.

Related

MySQL - Having problems with COUNT() in query with GROUP BY

I have a pretty big query which is used by an ajax call to return and also sort active items. From my understanding sub queries should be avoided where possible and since this query will be called very often, I would like to do just that.
At the moment everything is fine except for the COUNT(b.bic) AS bids. If there are two(2) bids the query returns four(4), if there are 4, it returns 8, and so on. I've tried grouping by other columns ... but no luck.
Some of the tables. I hope each of the column names are pretty self explanatory:
countries_ship - each item can be shipped to multiple countries so item_id can be duplicate.
id item_id country_id ship_cost
countries
id country_code country_name
item_expire - not sure if item_expire should have it's own table.
id item_id exp_date
bids - Just as countries_ship, item_id can be duplicate. This is where the bids are stored.
id item_id user_id bid previous_bid bid_date
The query:
$q = $this->db->mysqli->prepare("
SELECT c.ship_cost,
c.item_id,
co.country_name,
co.id AS co_id,
i.id,
i.user_id,
i.item_start,
i.item_title,
i.item_number,
i.item_year,
i.item_publisher,
i.item_condition,
i.item_description,
i.item_location,
e.exp_date AS exp_date,
i.active,
CAST(u.fb_id AS CHAR(50)) AS fb_id,
u.user_pic,
MAX(b.bid) AS maxbid,
COUNT(b.bid) AS bids,
p.publisher_name,
t.tag_name
FROM countries_ship c
JOIN items i
ON c.item_id = i.id
JOIN item_expire e
ON c.item_id = e.item_id
JOIN users u
ON i.user_id = u.id
LEFT JOIN bids b
ON i.id = b.item_id
LEFT JOIN publishers p
ON i.item_publisher = p.id
LEFT JOIN tags_rel tr
ON c.item_id = tr.item_id
JOIN tags t
ON t.id = tr.tag_id
LEFT JOIN countries co
ON i.item_location = co.id
WHERE ".$where."
GROUP BY c.item_id ORDER BY ".$order." ".$limit."");
You may try
COUNT(distinct b.bic) AS bids
This will ignore duplicates due to joins

Trying to JOIN an empty table nothing returns

I have a problem trying to JOIN an empty table (comments table) to my existing prepared statement.
This is working perfectly:
// prepare images
if ($stmt = $mysqli->prepare(" SELECT uu.*, m.*,
(
SELECT COUNT(*)
FROM img_likes AS t
WHERE t.img_id = uu.imgID AND t.user_id = ?
) AS user_likes,
(
SELECT COUNT(*)
FROM img_likes AS t
WHERE t.img_id = uu.imgID
) AS total_likes
FROM user_uploads AS uu
INNER JOIN members AS m ON m.id = uu.user_id
ORDER BY up_time DESC")) {
$stmt->bind_param('i', $user_id);
$stmt->execute(); // get imgs
// foreach print images
// working as expected
}
And I don't know why if I JOIN another table (img_comments) that is empty, the images are not printed... if I add a row to the table and refresh the page, one image is printed...
The statement that I'm trying and it's not working is this:
SELECT uu.*, m.*, ic.*,
(
SELECT COUNT(*)
FROM img_likes AS t
WHERE t.img_id = uu.imgID AND t.user_id = ?
) AS user_likes,
(
SELECT COUNT(*)
FROM img_likes AS t
WHERE t.img_id = uu.imgID
) AS total_likes
FROM user_uploads AS uu
INNER JOIN members AS m ON m.id = uu.user_id
INNER JOIN img_comments AS ic ON ic.img_id = uu.imgID
ORDER BY up_time DESC
Why is only printing images based on the number of the table rows?? I also tried LEFT JOIN but I'm not too familiareize with this. I only use INNER JOIN in other scripts and I never had a problem like this.
I would appreciate any optimization to my query.
What does an inner join do? It joins all records of table a with all matching records of table b. So when there are no records in table b, there is no match for any record of table a, hence no result at all. Why does this surprise you?
A left join is an outer join (short for LEFT OUTER JOIN). It means: Give me all records of table a with all matching records of table b, and when there is no match then give me the record of table a anyhow. This seems to be what you are wanting here. But you say you tried it. I don't see how this would fail in your query.
A typical error for an outer join not to work would be to have some field of b in your where clause (e.g. where b.id > 100). As the outer-joined records have no matching b record, all b fields are null, so that such a where clause would fail. You'd just get matches again, just like with the inner join.
EDIT: As to optimization, you can get the two counts in one pass by counting conditionally:
SELECT
uu.*, m.*, ic.*,
il.count_user AS user_likes,
il.count_total AS total_likes
FROM user_uploads AS uu
INNER JOIN members AS m ON m.id = uu.user_id
LEFT OUTER JOIN img_comments AS ic ON ic.img_id = uu.imgID
LEFT OUTER JOIN
(
select
img_id,
count(*) as count_total,
count(case when t.user_id = ? then 1 end) as count_user
from img_likes
group by img_id
) AS il ON il.img_id = uu.imgID
ORDER BY uu.up_time DESC;
As far as I know, INNER JOIN will only retrieve data which have both data. So if let say the table that you join have no data with that join condition. It will not return any data at all.
LEFT JOIN is just a normal join. It will retrieve data on both table. But if the joined table is empty, then only the primary table will have data, the secondary table will have null as its data.
You can just modify your code, replacing INNER JOIN with LEFT JOIN and see if it works/

Loading details from multiple tables

I was using this:
SELECT res.*, rac.*, u.*, t.*, c.*
FROM Results res
INNER JOIN Races rac USING (RaceID)
INNER JOIN Users u USING (UserID)
INNER JOIN Teams t USING (TeamID)
INNER JOIN Cars c USING (CarID)
WHERE res.SeasonNumber = '$SeasonNumber' AND res.LeagueID = '$LeagueID' AND Position = '1' AND ResultConfirmed = '1'
ORDER BY Position ASC
Which works fine, but I've since realised I need to have CarID added in to Results table, but when I add it in, it gives me the error that the field is ambiguous. What I'd like to do is get the Car name from Cars table where CarID joins Cars and Results. When I try to do this though:
SELECT res.*, rac.*, u.*, t.*, c.*
FROM Results res
INNER JOIN Races rac USING (RaceID)
INNER JOIN Users u USING (UserID)
INNER JOIN Teams t USING (TeamID)
INNER JOIN Cars c USING (res.CarID)
WHERE res.SeasonNumber = '$SeasonNumber' AND res.LeagueID = '$LeagueID' AND Position = '1' AND ResultConfirmed = '1'
ORDER BY Position ASC
I get the following error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '.CarID) WHERE res.SeasonNumber = '1' AND res.LeagueID = '1' AND
Position = '1' ' at line 6
You can replace your USING clause with ON(),in USING() clause i guess you add the columns name that are same in other table you are joining but you placed the join in last and using alias res mysql won't allow this
INNER JOIN Cars c ON(res.CarID =c.CarID)
If you need to use USING() clause you need to adjust the join placements like
SELECT res.*, rac.*, u.*, t.*, c.*
FROM
Cars c
INNER JOIN Results res USING (CarID)
INNER JOIN Races rac USING (RaceID)
INNER JOIN Users u USING (UserID)
INNER JOIN Teams t USING (TeamID)
WHERE res.SeasonNumber = '$SeasonNumber' AND res.LeagueID = '$LeagueID' AND Position = '1' AND ResultConfirmed = '1'
ORDER BY Position ASC
But ON() clause is more readable form

PHP/MYSQL Query if not in second table

I have two tables. I want to draw a sample of the first table except where the person in the first table is also in a second table. Am having trouble doing this seemingly simple query.
table users
id|name
table catuser
id|userid|catid
I have tried
SELECT u.*,c.userid FROM `users` u
LEFT JOIN `catuser` c
ON (u.id = c.userid AND c.userid <> '197')
WHERE u.id = '1'
and variations to no avail. Would appreciate any suggestions.
How abt. this:
SELECT u.*,c.userid
FROM `users` u
LEFT JOIN `catuser` c
ON u.id = c.userid
WHERE u.id = '1'
AND c.userid <> '197'
AND c.userid is null
SELECT * FROM users WHERE id NOT IN (SELECT DISTINCT userid FROM catuser)
If you want to query only users that have one or more categories, you can use a WHERE EXISTS query:
SELECT u.* FROM `users` u
WHERE EXISTS (SELECT * FROM catuser WHERE catuser.userid = u.id)
Another possibility is to do a left join, and check whether the join succeeded on checking on null:
SELECT u.*, c.* FROM `users` u
LEFT JOIN catuser c ON u.id = c.userid
WHERE c.id IS NOT NULL
If there is no corresponding row in catuser, all catuser fields will be null. By checking whether c.id is not null, you only include the rows with a category.
Note that the join may return a user multiple time, if he is in multiple categories.

Avoid multiple LEFT JOIN

Is there a way to avoid adding a second LEFT JOIN for the table "social_mcouple" to query where social_members.m_id = social_mcouple.c_id below?
$res = #mysql_query("SELECT *, DATE_FORMAT(m_lld,'%m/%d/%y') AS m_lld_formatted FROM social_members
LEFT JOIN social_member_types ON t_id=m_type WHERE m_user='".$en['user']."'");
If there will always be a social_mcouple that corresponds to social_members, or you're only interested in rows where there is a correspondence then you may use an INNER JOIN. If you need all social_members regardless of whether there is a corresponding social_mcouple then you will need a LEFT JOIN. The LEFT JOIN will give you all rows with social_mcouple.* set to NULL where there is not a match.
The performance hit will really depend on the size of your datasets.
EDIT: adding a sample UNION query.
$res = #mysql_query("
(SELECT social_members.*, social_member_types.*, DATE_FORMAT(m_lld,'%m/%d/%y') AS m_lld_formatted,
NULL AS mcouple1, NULL AS mcouple2, NULL AS mcouple3
FROM social_members
LEFT JOIN social_member_types ON t_id=m_type
WHERE m_user='".$en['user']."' AND m_type != 2)
UNION
(SELECT social_members.*, social_member_types.*, DATE_FORMAT(m_lld,'%m/%d/%y') AS m_lld_formatted,
social_mcouple.mcouple1, social_mcouple.mcouple2, social_mcouple.mcouple3
FROM social_members
LEFT JOIN social_member_types ON t_id=m_type
JOIN social_mcouple ON social_members.m_id = social_mcouple.c_id
WHERE m_user='".$en['user']."' AND m_type = 2)
");

Categories