Thank to your help I made a view in my database called 'people' that retrieve data using three functions called 'isUserVerified', 'hasUserPicture' and 'userHobbies' from two tables called 'users' and 'user_hobbies':
SELECT
`u`.`id` AS `id`,
`isUserVerified`(`u`.`id`) AS `verification`,
`hasUserPicture`(`u`.id) AS `profile_picture`,
`userHobbies`(`h`.`user_id`) AS `hobbies`
FROM
`people`.`users` u
INNER JOIN
`people`.`user_hobbies` h
ON
`h`.`user_id` = `u`.`id`
It returns the following output:
I realise that this is because I am joining on:
`h`.`user_id` = `u`.`id`
But it is not what I want. For each user I want to run the tree function and return if they are verified, have a profile picture and a hobby. I am expecting 10 users with the relative information. Can you help? Thank you
I don't think you need to join to hobbies at all. Your functions are doing the work for you:
SELECT u.id,
isUserVerified(u.id) AS verification,
hasUserPicture(u.id) AS profile_picture,
userHobbies(u.id) AS hobbies
FROM people.users u;
Note that user-defined functions tend to slow queries down, sometimes a lot. Functions may be a good idea in some languages, but in SQL it is better to express the logic as JOINs and GROUP BYs.
Also, there is no reason to use backticks if the identifiers don't have "bad" characters. Unnecessary backticks just make the query harder to write and read.
You can replace INNER JOIN with LEFT JOIN to see all of the users, since users table is stated on the left of the JOIN keyword, and INNER looksup for the exact match in the condition. e.g. if there's no spesific user id inserted into the hobbies table, the related row is not returned by INNER JOIN.
Related
I have 2 tables, one is setting and one is accounts
setting has columns of: isVerified, customMessage, user
accounts has columns of: id, fullName, password, address, phone
I know I have to do join but how do I get only fullName from accounts table?
I did this
SELECT isVerified, customMessage, fullName
FROM setting FULL OUTER JOIN
accounts
ON setting.user = accounts.id;
but got error near the JOIN. What's wrong?
An inner join should suffice:
SELECT s.isVerified, s.customMessage, a.fullName
FROM setting s INNER JOIN
accounts a
ON s.user = a.id;
MySQL does not support FULL OUTER JOIN. Presumably, all accounts have settings and vice versa.
Note that I introduced table aliases so the query is easier to write and to read. And, in this query, all column names specify the table they come from.
I know I have to do join but how do I get only fullName from accounts
table?
If you only want fullName only specify fullName column in your select statement.
Select fullname FROM ....
As others have pointed out MySQL doesn't support FULL OUTER JOIN so change that to simply JOIN as Gordon Linoff has mentioned above.
Normally when you do a join you either want rows that match both the tables (setting and accounts in your case). Based on the columns you've described and depending on how you've designed your schema it's either a One to One relationship between two tables or One to Many. Your case sounds like one to one as each users account will have a setting.
You're joining on s.user = a.id but I don't see you mentioned s.user is actually same as a.id? What is the user field? Perhaps you need to name this better as s.id if it's actually an id. As others have pointed out please include your actual table definition so it's easier to figure out why you get the SQL error while running your query.
Good luck.
How can I create a single sql command to display the statements of accounts of one of the customer using inner join? help please, thanks.
I see that your custumers are identified by the telephone number, i don't think that is a good idea, since telephone number can change quite often in your custumer table, anyway this should be the query.
SELECT SA.* FROM STATAMENT_OF_ACCOUNT_TBL SA
JOIN OFFICIAL_RECEIP_TBL R ON SA.STATEMENT_ACC_NO=R.STATEMENT_ACC_NO
JOIN CUSTUMER_TBL C ON C.CUS_TEL_NO=R.CUS_TEL_NO
WHERE C.CUS_TEL_NO='422-9418'
Ah, and there should not be null on the keys you are trying to join or it could result in nothing as results.
Lets say I have the following query:
SELECT occurs.*, events.*
FROM occurs
INNER JOIN events ON (events.event_id = occurs.event_id)
WHERE event.event_state = 'visible'
Another way to do the same query and get the same results would be:
SELECT occurs.*, events.*
FROM occurs
INNER JOIN events ON (events.event_id = occurs.event_id
AND event.event_state = 'visible')
My question. Is there a real difference? Is one way faster than the other? Why would I choose one way over the other?
For an INNER JOIN, there's no conceptual difference between putting a condition in ON and in WHERE. It's a common practice to use ON for conditions that connect a key in one table to a foreign key in another table, such as your event_id, so that other people maintaining your code can see how the tables relate.
If you suspect that your database engine is mis-optimizing a query plan, you can try it both ways. Make sure to time the query several times to isolate the effect of caching, and make sure to run ANALYZE TABLE occurs and ANALYZE TABLE events to provide more info to the optimizer about the distribution of keys. If you do find a difference, have the database engine EXPLAIN the query plans it generates. If there's a gross mis-optimization, you can create an Oracle account and file a feature request against MySQL to optimize a particular query better.
But for a LEFT JOIN, there's a big difference. A LEFT JOIN is often used to add details from a separate table if the details exist or return the rows without details if they do not. This query will return result rows with NULL values for b.* if no row of b matches both conditions:
SELECT a.*, b.*
FROM a
LEFT JOIN b
ON (condition_one
AND condition_two)
WHERE condition_three
Whereas this one will completely omit results that do not match condition_two:
SELECT a.*, b.*
FROM a
LEFT JOIN b ON some_condition
WHERE condition_two
AND condition_three
Code in this answer is dual licensed: CC BY-SA 3.0 or the MIT License as published by OSI.
In the article Why Arel?, the author poses the problem:
Suppose we have a users table and a photos table and we want to select all user data and a *count* of the photos they have created.
His proposed solution (with a line break added) is
SELECT users.*, photos_aggregation.cnt
FROM users
LEFT OUTER JOIN (SELECT user_id, count(*) as cnt FROM photos GROUP BY user_id)
AS photos_aggregation
ON photos_aggregation.user_id = users.id
When I attempted to write such a query, I came up with
select users.*, if(count(photos.id) = 0, null, count(photos.id)) as cnt
from users
left join photos on photos.user_id = users.id
group by users.id
(The if() in the column list is just to get it to behave the same when a user has no photos.)
The author of the article goes on to say
Only advanced SQL programmers know how to write this (I’ve often asked this question in job interviews I’ve never once seen anybody get it right). And it shouldn’t be hard!
I don't consider myself an "advanced SQL programmer", so I assume I'm missing something subtle. What am I missing?
I believe your version would produce an error, at least in some database engines. In MSSQL your select would generate [Column Name] is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.. This is because you select can only contain values in the group by or the count.
You could modify your version to select users.id, count(photo.id) and it would work, but it would not be the same result as his query.
I would not say you have to be particularly advanced to come up with a working solution (or the specific solution he came up with) but it is necessary to do the group in a separate query either in the join or as #ron tornambe suggests.
In most DBMSs (MySQL and Postgres are exceptions) the version in your question would be invalid.
You would need to write the query which does not use the derived table as
select users.*, CASE WHEN count(photos.id) > 0 THEN count(photos.id) END as cnt
from users
left join photos on photos.user_id = users.id
group by users.id, users.name, users.email /* and so on*/
MySQL allows you to select non aggregated items that are not in the group by list but this is only safe if they are functionally dependant on the column(s) in the group by.
Whilst the group by list is more verbose without the derived table I would expect most optimisers to be able to transform one to the other anyway. Certainly in SQL Server if it sees you are grouping by the PK and some other columns it doesn't actually do group by comparisons on those other columns.
Some discussion about this MySQL behaviour vs standard SQL is in Debunking GROUP BY myths
Maybe the author of the article is wrong. Your solution works as well, and it may very well be faster.
Personally, I would drop the if alltogether. If you want to count the number of pictures, it makes sense that 'no pictures' results in 0 rather than null.
As an alternative, you can also write a correlated sub-query:
SELECT u.*, (SELECT Count(*) FROM photos p WHERE p.userid=u.id) as cnt
FROM users u
There are 4 sql tables:
Listings(Amount, GroupKey, Key, MemberKey),
Loans(Amount, GroupKey, Key, ListingKey),
Members(City, GroupKey, Key)
Groups(GroupRank, Key, MemberKey)
Now, if one wants to find out the loans which are also listings and find the members city and GroupRank for the members in the loan table. Here, the group table contains information about grous of which members are a part of.
and also perform a select operation as given below:
select Listings.Amount, Members.City, Groups.GroupRank
from listings, loans, members, groups
where Listings.Key=Loans.ListingKey and
Members.Key=Listings.MemberKey and
Listings.GroupKey=Groups.Key
The above join is giving an incorrect result, please point out where I am going wrong.
Also I am new to SQL so please excuse the novice question.
Note: The following is just a guess what your problem is. Like others said, clearify your question.
You want to JOIN
( http://dev.mysql.com/doc/refman/5.1/de/join.html )
those tables. What you write is just another form of a join, meaning it has the same effect. But you "joined" a bit too much. To make things clearer a syntax has been invented to make things clearer and avoid such mistakes. Read more about it in the link given above.
What you want to achieve can be done like this:
SELECT
Listings.Amount, Members.City, Groups.GroupRank
FROM
Listings
INNER JOIN Groups ON Listings.GroupKey=Groups.Key
INNER JOIN Members ON Members.Key=Listings.MemberKey
You don't do a SELECT on the Loans table, you don't need it in this query.
This is the INNER JOIN which will give you a result where every row in table A has an according entry in table B. When this is not the case, you have to use the LEFT or RIGHT JOIN.
Maybe the problem is related to the join type (INNER). Try LEFT JOIN for example but Mark has right: you should clearify your question.
I would firstly change your query to use the more modern join syntax, which allows outer joins. Tr this:
select Listings.Amount, Members.City, Groups.GroupRank
from listings
left join loans on Listings.Key=Loans.ListingKey
left join members on Members.Key=Listings.MemberKey
left join groups on Listings.GroupKey=Groups.Key
and/or Loans.GroupKey=Groups.Key
and/or Members.Key=Groups.MemberKey
You may need to play with the criteria on the last join (maybe they should be "or" not "and" etc).