MySQL If Else Statment - php

Here is an example query:
SELECT tags.serial_number, tags.expiry_date, tags.activation_date, users.email, users.offers, users.newsletter, pets.name as petname
FROM `tags`
JOIN `users` on users.id = tags.user_id
JOIN `pets` on pets.id = tags.pet_id
WHERE users.username = 'myusername' AND users.email = 'itsme#mydomain.com'
In this scenario, the only results that will be returned are those tags that are assigned to both a user and a pet. But what I want is to be able to receive all tags, regardless of whether or not they are assigned to a pet.
If there some kind of "IF there is a pet, show the petname, ELSE just return the pet name as NULL" or something like that?

Try using a Left Outer Join Which will populate rows that don't join to the table with Nulls
SELECT tags.serial_number, tags.expiry_date, tags.activation_date, users.email, users.offers, users.newsletter, pets.name as petname
FROM `tags`
JOIN `users` on users.id = tags.user_id
Left Outer JOIN `pets` on pets.id = tags.pet_id
WHERE users.username = 'myusername' AND users.email = 'itsme#mydomain.com'

The quick answer is to use LEFT JOIN in place of JOIN.
(I'm sure this question has asked on StackOverflow before ...)

Related

SQL LEFT JOIN & AND Keyword

Currently have a function which uses the following SQL statement:
SELECT `plans`.`concurrents`
FROM `plans`
LEFT JOIN `users` ON `users`.`membership` = `plans`.`ID`
WHERE `users`.`ID` = ?`
I am trying to add into the SQL statement so it also adds on the value within the 'extra_concurrents' column in the 'users' table to the value which is returned from the SQL statement above.
I tried but have no luck:
SELECT `plans`.`concurrents`
FROM `plans`
LEFT JOIN `users` ON `users`.`membership` AND `users`.`extra_concurrents` = `plans`.`ID`
WHERE `users`.`ID` = ?`
I need to return the total value of plans.concurrents and users.extra_concurrents added together
I need to say something about your query. The left join is utterly unnecessary. Your where clause is turning it into an inner join.
Then, I recommend table aliases, to simplify the query. And the rest is addition:
SELECT p.concurrents + coalesce(u.extra_concurrents, 0)
FROM plans p JOIN
users u
ON u.membership = p.ID
WHERE u.ID = ?;
Also notice the coalesce(), just in case the users.extra_concurrents column is NULL.
When you join the tables you can call the columns from the other table
SELECT `plans`.`concurrents`,`users`.`extra_concurrents`
FROM `plans`
LEFT JOIN `users` ON `users`.`membership` = `plans`.`ID`
WHERE `users`.`ID` = ?`
You'll need to use multiple joins instead of an "and". Without seeing your data structure it's hard to say exactly what you'll need, but probably something like this:
SELECT `plans`.`concurrents`
FROM `plans` `A`
LEFT JOIN `users` `B` ON `B`.`membership` = `A`.`ID`
INNER JOIN `users` `C` ON `C`.`extra_concurrents` = `A`.`ID`
WHERE `users`.`ID` = ?`
SELECT sum((`plans`.`concurrents`)+(`users`.`extra_concurrents`))
FROM `plans`
LEFT JOIN `users` ON `users`.`membership` = `plans`.`ID`
WHERE `users`.`ID` = ?`
Note : its not good to add where condition on Left table.
Good Luck

How to join three MySQL tables with unrelated data?

So I have a webpage that shows an image and information about it, and I also have three tables.
IMAGES USERS COMMENTS
id user_id id
user_id username user_id
username password comment
title isadmin date
image (location) points
description signup_date
points email
category city
bio
profile_image
I need to use all the information from the images and comments table. But I also need to retrieve the profile_image of the user that posted the comment and image. I cannot figure out how to do this: here is what I have so far.
$conn = new PDO ("mysql:host=localhost;dbname=project", "root", "pass");
$stmt = $conn->prepare("
SELECT images.*, users.profile_image, comments.*
FROM (images.id JOIN comments ON images.id = comments.id)
LEFT JOIN users
ON images.user_id = user.profile_image
");
Am I close? or trying the impossible here!?
it's a lot simpler then you'd think :)
the tables are NOT unrelated, they all have the same key - user_id and that's how you join them.
your query should look like this:
SELECT images.*, users.profile_image, comments.*
FROM images
JOIN users ON images.user_id = users.user_id
JOIN comments ON comments.user_id = users.user_id AND images.id = comments.id
this is assuming the images.id and comments.id match (I suspect they do not - but you did not give us enough info)
looking at your table structure, comments and images appear to have no connection, so maybe query them separately to avoid duplicated & confusing data
---UPDATE---
assuming you've added image_id to comments this is your query:
SELECT images.*, users.profile_image, comments.*
FROM images
LEFT JOIN users ON images.user_id = users.user_id
LEFT JOIN comments ON comments.user_id = users.user_id AND images.id = comments.image_id
what LEFT JOIN does is return 'images' that don't necessarily have 'users' or 'comments' connected to them.
I guess this will do the trick:
SELECT i.*, u.profile_image, c.*
FROM images i
LEFT JOIN comments c ON i.user_id = c.user_id
LEFT JOIN users u ON i.user_id = u.user_id
I think it's:
> SELECT images.*, users.profile_image, comments.*
> FROM images
> INNER JOIN users ON images.user_id= users.user_id
> INNER JOIN comments ON users.user_id= comments.user_id

getting data from four tables with tight WHERE clause

i need help getting data from different tables and insert into other different table Here are the Queries
"SELECT commentID, date, comment, subject, parentID, aBUserID FROM comments WHERE status = 'APPROVED'"
"SELECT topicID, subForumID, aBUserID, lastPostID, views, replies, startDate FROM topic WHERE status = 'APPROVED' AND topicID = $parentid";
// $parentID need to be matched from above query parentID,
"SELECT userName FROM users WHERE aBUserID = $cmtaBUserID";
// $cmtaBUserID = aBUserID from first query
"SELECT userName FROM users WHERE aBUserID = $topicaBUserID";
//$topicaBUserID = aBUserID from second query
Last 2 queries are from same table but using different where clause
i used different inner join left join from solutions posted here but non of these worked for me stuck since last 2 weeks please help
PS data from all above Queries will be inserted to a single table i need these to be combined so i can have them all in one place
If you want to perform the operation in same query use 'OR'
"SELECT userName FROM users WHERE aBUserID = $cmtaBUserID OR aBUserID = $topicaBUserID";
Please try this
SELECT userName from users where aBUserID IN(SELECT aBUserID FROM comments WHERE status = 'APPROVED')
Couldn't test it but Maybe this is what you are looking for.
SELECT c.commentID, c.date, c.comment, c.subject, c.parentID, c.aBUserID,
t.topicID, t.subForumID, t.aBUserID, t.lastPostID, t.views, t.replies, t.startDate,
u.userName
FROM
comments c
left outer join topic t on t.topicID = c.parentID
left outer join users u on u.aBUserID = c.aBUserID and u.aBUserID = t.aBUserID
WHERE
c.status = 'APPROVED' and t.status = 'APPROVED';
try this:
SELECT
comment.[commentID],
comment.[date],
comment.[comment],
comment.[subject],
comment.[parentID],
comment.[aBUserID],
commentuser.[userName],
topic.[topicID],
topic.[subForumID],
topic.[aBUserID],
topic.[lastPostID],
topic.[views],
topic.[replies],
topic.[startDate],
topic.[userName]
FROM comments comment
LEFT OUTER JOIN users commentuser
ON commentuser.aBUserID = comment.[aBUserID]
LEFT OUTER JOIN
(
SELECT
t.[topicID],
t.[subForumID],
t.[aBUserID],
t.[lastPostID],
t.[views],
t.[replies],
t.[startDate],
u2.[userName] --user from users table joined to topics table
FROM topic t
LEFT OUTER JOIN users u
ON u.aBUserID = t.[aBUserID]
WHERE t.[status] = 'APPROVED'
) topic
ON topic.topicID = comment.parentID
WHERE comment.[status] = 'APPROVED'

What's wrong with this MySQL query (uses LEFT OUTER JOIN)?

I'm trying to make a query that returns the following:
All users such that:
-They are not an admin or owner account
-They have the same client_id as the project's client_id
-They are not already in the project_users table with entry project_users.project_id = 9
Here is my MySQL query:
SELECT `users`.`id` as id, `users`.`first_name` as first_name, `users`.`last_name` as last_name, `users`.`username` as username
FROM (`users`)
JOIN `projects` ON `projects`.`client_id` = `users`.`client_id` AND projects.id = 9
LEFT OUTER JOIN `project_users` ON `users`.`id` = `project_users`.`user_id`
WHERE `users`.`user_type` != 'Admin'
AND `users`.`user_type` != 'Owner'
For some reason, this query seems to return all non-super(not owner or admin) users with the same client_id as the project, but does NOT exclude those already in the project_users table (ie. the LEFT OUTER JOIN statement isn't working).
Can anyone tell me what is wrong with the query?
Thanks!
You need to add a filter to find the rows that don't match. Also, your query can be helped by using table aliases:
SELECT u.`id` as id, u.`first_name` as first_name, u.`last_name` as last_name, u.`username` as username
FROM `users` u JOIN
`projects` p
ON p.`client_id` = u.`client_id` AND p.id = 9 LEFT OUTER JOIN
`project_users` pu
ON u.`id` = pu.`user_id`
WHERE u.`user_type` not in ('Admin', 'Owner') and
pu.user_id is NULL;

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.

Categories