I'm making the below query:
SELECT
`user_organisation`.*,
`users`.`full_name`,
`users`.`email`,
`users`.`avatar`
FROM
`user_organisation`
INNER JOIN `users` ON `users`.`id` = `user_organisation`.`user_id`
WHERE
`users`.`full_name` LIKE '%test%' OR `users`.`email` LIKE '%test%' AND `user_organisation`.`organisation_id` = 111
And I get the results containing user_organisation.organisation_id equals 111 and 222. I want to search records with users.full_name or users.email containing value test. This SQL successfully searches users with full name or email containing string test but not only user_organisation.organisation_id=111.
What the reason for that unexpected behaviour? I sure I'm missing something but I can't see...
You need parentheses in your WHERE clause around the two ORed terms:
SELECT uo.*, u.full_name, u.email, u.avatar
FROM user_organisation uo
INNER JOIN users u ON u.id = uo.user_id
WHERE (u.full_name LIKE '%test%' OR u.email LIKE '%test%') AND
uo.organisation_id = 111;
Note also that in my answer I am using table aliases (which are abbreviations for full table names). Also, I removed the unnecessary backticks.
Related
I have a query that works perfectly, however I need to change it a bit but it shows me an error and I can't figure out why. Below is the code before and after the changes I made:
BEFORE:
SELECT *,
(SELECT GROUP_CONCAT(pho_file_name) FROM post_images WHERE pho_post_id=posts.ID) AS photo_file_array
FROM users
INNER JOIN posts ON users.Id = posts.post_author
ORDER BY posts.ID;
AFTER:
SELECT *,
(SELECT GROUP_CONCAT(pho_file_name) FROM post_images WHERE pho_post_id=posts.ID) AS photo_file_array
FROM users WHERE users.Id = "1"
INNER JOIN posts ON users.Id = posts.post_author ON posts.post_date = "2020-12-04 07:51:21"
ORDER BY posts.ID;
It shows me the following error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INNER JOIN posts ON users.Id = posts.post_author AND posts.post_date "2020-12...' at line 4
I'm a newbie on MySql but from what I can understand I think the error occurs because of the the double ON inside the INNER JOIN. So, is it possible to add multiple ON inside the INNER JOIN? Thanks in advance!!
You have a few syntax issues, you can't put joins and where anywhere, you also need to use the correct delimiters and data types.
Try the following and note using table and column aliases makes for an easier-to-read query.
Additionally, consider not using select * and reference only the columns you actually require, if possible.
SELECT u.*, p.*, (
SELECT GROUP_CONCAT(i.pho_file_name)
FROM post_images i
WHERE i.pho_post_id = p.ID
) AS photo_file_array
FROM users u
JOIN posts p ON p.post_author = u.Id
AND p.post_date = '2020-12-04 07:51:21'
WHERE u.Id = 1
ORDER BY p.ID;
Here is a full working query. The errors (double ONclause, WHERE clause in the wrong position, wrong quotes) are corrected. Moreover, the ID is compared to an integer now and the post_date to a timestamp literal. I've used table aliases to get this more readable.
SELECT
u.*,
p.*,
(
SELECT GROUP_CONCAT(pi.pho_file_name)
FROM post_images pi
WHERE pi.pho_post_id = p.id
) AS photo_file_array
FROM users u
INNER JOIN posts p ON p.post_author = u.id
AND p.post_date = TIMESTAMP '2020-12-04 07:51:21'
WHERE u.id = 1
ORDER BY p.id;
As to the tables: I suggest you are more consistent with your column names. Why do you call the post ID post_author? One would assume a name here. Just call it post_id in every table. And you don't have to precede columns with abreviations like pho. Just qualify all columns with their tables like I did in my query.
I have the following mysql select. It gets the list of the users qualified on the event and it also gets some results from the users table.
SELECT event.*,
users.first_name,
users.last_name,
users.login,
users.email,
users.f_phone as userphone,
users.f_phone_code
FROM event,
users
WHERE (users.id=event.h_user and f_code LIKE %NEW%)
OR event.h_user = -1
ORDER BY event.`h_id` DESC
Everything worked perfectly, until I tried to get more results by adding the records with h_user = -1. There is not a lot of them, but I guess my query isn't good enough while the database of users is really big. The added OR statement is crashing database while getting results. I tried to add the brackets in WHERE statement but they arent helping.
Would you mind to help me on this please?
It happens because your implicit join conditions become messed up when u add or in the where clause, thus the query doesn't work as you expect it to. Try using explicit join instead (u can make the query work both ways, but explicit notation is just more readable) and leave all the filtering in the where clause:
from event
join users on users.id = event.h_user
where f_code like '%NEW%' or event.h_user = -1
Which would look like this using the implicit notation (don't use it, it is deprecated):
from event, users
where ( users.id = event.h_user ) and
( f_code like '%NEW%' or event.h_user = -1 )
You could also do this with joins and a UNION:
SELECT event.*,
users.first_name,
users.last_name,
users.login,
users.email,
users.f_phone as userphone,
users.f_phone_code
FROM event
INNER JOIN users ON users.id=event.h_user
WHERE f_code LIKE %NEW%
UNION
SELECT event.*,
users.first_name,
users.last_name,
users.login,
users.email,
users.f_phone as userphone,
users.f_phone_code
FROM event
INNER JOIN users ON users.id=event.h_user
WHERE event.h_user = -1
ORDER BY event.`h_id` DESC
I'm trying to run this code but i'm getting errors.
Any ideas why?
SELECT notes.project_id, notes.title, notes.description
FROM notes, project_members
WHERE notes.title LIKE '%second%' OR notes.description LIKE '%second%'
WHERE notes.project_id = project_members.project_id AND project_members.user_id = '7'
Since you only can have one WHERE clause you could use a inner join like this:
SELECT notes.project_id, notes.title, notes.description
FROM project_members pm
INNER JOIN notes ON notes.project_id = pm.project_id AND pm.user_id = 7
WHERE notes.title LIKE '%second%' OR notes.description LIKE '%second%'
You have two WHERE clauses, but single SELECT only allows one. But, this would easily be fixed if you used proper, explicit JOIN syntax:
SELECT n.project_id, n.title, n.description
FROM notes n JOIN
project_members p
ON n.project_id = p.project_id
WHERE (n.title LIKE '%second%' OR n.description LIKE '%second%') AND
p.user_id = '7';
Note:
Always use proper, explicit JOIN syntax. Never use commas in the FROM clause.
Table aliases make the query easier to write and to read.
I'm pretty sure your WHERE conditions are missing parentheses, for your intended logic.
If user_id is a number of any sort, then don't use single quotes around "7". This can confuse both the compiler and people.
There should be single WHERE clause.
SELECT notes.project_id, notes.title, notes.description
FROM notes, project_members
WHERE
(notes.title LIKE '%second%' OR notes.description LIKE '%second%')
AND notes.project_id = project_members.project_id AND project_members.user_id = '7';
Query would look something above to AND between your LIKE conditions.
You may also consider using JOIN, Like this.
SELECT notes.project_id, notes.title, notes.description
FROM notes
JOIN project_members
ON notes.project_id=project_members.project_id
WHERE
(notes.title LIKE '%second%' OR notes.description LIKE '%second%')
AND project_members.user_id = '7';
I need something similar to this ... but its not working obviously, not sure if I need to use any JOIN's or what. Much help is appreciated! Thanks.
vicidial_closer_log.user = vicidial_users.user = vicidial_campaign_agents.user
SELECT
vicidial_closer_log.call_date,
Count(vicidial_closer_log.`status`) AS call_count,
vicidial_closer_log.`user`,
vicidial_closer_log.user_group,
vicidial_users.`user`,
vicidial_users.full_name,
vicidial_campaign_agents.`user`,
vicidial_campaign_agents.campaign_rank
FROM
vicidial_closer_log ,
vicidial_users ,
vicidial_campaign_agents
WHERE
date_format(vicidial_closer_log.call_date, '%Y-%m-%d') BETWEEN '2014-04-02' AND '2014-04-02' AND
vicidial_closer_log.`user` NOT LIKE 'VDCL' AND
vicidial_closer_log.`status` NOT LIKE 'CS' AND
vicidial_closer_log.`status` NOT LIKE 'NANQUE' AND
vicidial_closer_log.`status` NOT LIKE 'TIMEOT' AND
vicidial_closer_log.user_group IN ('RAD_US', 'RAD_JAM') AND
vicidial_closer_log.`user` = vicidial_users.`user`
GROUP BY
vicidial_closer_log.`user`
ORDER BY
vicidial_closer_log.`user` ASC
The way you were doing putting the [vicidial_closer_log.user = vicidial_users.user] on WHERE clause isn't completly wrong, but you forgot to link the vicidial_campaign_agents table. If you add a
AND vicidial_users.user = vicidial_campaign_agents.user
at the end of WHERE clause should work to, but try getting used to the JOIN clause. It's the right way of doing it and makes your query look prettier.
The JOIN clause is very simple, works like this: table_a JOIN table_b ON table_a.key = table_b.key. The ON clause specifies what column must match between table_a and table_b and then you JOIN the result of this with table_c doing the same thing.
LIKE THIS:
SELECT
l.call_date,
Count(l.status) AS call_count,
l.user,
l.user_group,
u.full_name,
a.campaign_rank
FROM
vicidial_closer_log l
JOIN vicidial_users u ON l.user = u.user
JOIN vicidial_campaign_agents a ON u.user = a.user
WHERE
date_format(l.call_date, '%Y-%m-%d') BETWEEN '2014-04-02' AND '2014-04-02' AND
l.user <> 'VDCL' AND
l.status NOT IN ('CS', 'NANQUE', 'TIMEOT') AND
l.user_group IN ('RAD_US', 'RAD_JAM')
GROUP BY
l.user
ORDER BY
l.user ASC
I've also added alias to you tables, so your query gets cleaner.
And also, you don't neet simple quotes to specify table columns like table_a.'column', just type table_a.column.
And also, the part you typed
l.status NOT LIKE 'CS' AND
l.status NOT LIKE 'NANQUE' AND
l.status NOT LIKE 'TIMEOT'
you could have typed
l.status NOT IN ('CS', 'NANQUE', 'TIMEOT')
And also, you're selecting l.user, u.user and a.user. The way you described your query, these 3 columns will aways be identical on each line, so it's a waste of network traffic when downloading the resultset from the DB server.
I hope it works.
While working on a system I'm creating, I attempted to use the following query in my project:
SELECT
topics.id,
topics.name,
topics.post_count,
topics.view_count,
COUNT( posts.solved_post ) AS solved_post,
(SELECT users.username AS posted_by,
users.id AS posted_by_id
FROM users
WHERE users.id = posts.posted_by)
FROM topics
LEFT OUTER JOIN posts ON posts.topic_id = topics.id
WHERE topics.cat_id = :cat
GROUP BY topics.id
":cat" is bound by my PHP code as I'm using PDO. 2 is a valid value for ":cat".
That query though gives me an error: "#1241 - Operand should contain 1 column(s)"
What stumps me is that I would think that this query would work no problem. Selecting columns, then selecting two more from another table, and continuing on from there. I just can't figure out what the problem is.
Is there a simple fix to this, or another way to write my query?
Your subquery is selecting two columns, while you are using it to project one column (as part of the outer SELECT clause). You can only select one column from such a query in this context.
Consider joining to the users table instead; this will give you more flexibility when selecting what columns you want from users.
SELECT
topics.id,
topics.name,
topics.post_count,
topics.view_count,
COUNT( posts.solved_post ) AS solved_post,
users.username AS posted_by,
users.id AS posted_by_id
FROM topics
LEFT OUTER JOIN posts ON posts.topic_id = topics.id
LEFT OUTER JOIN users ON users.id = posts.posted_by
WHERE topics.cat_id = :cat
GROUP BY topics.id
In my case, the problem was that I sorrounded my columns selection with parenthesis by mistake:
SELECT (p.column1, p.column2, p.column3) FROM table1 p WHERE p.column1 = 1;
And has to be:
SELECT p.column1, p.column2, p.column3 FROM table1 p WHERE p.column1 = 1;
Sounds silly, but it was causing this error and it took some time to figure it out.
This error can also occur if you accidentally use commas instead of AND in the ON clause of a JOIN:
JOIN joined_table ON (joined_table.column = table.column, joined_table.column2 = table.column2)
^
should be AND, not a comma
This error can also occur if you accidentally use = instead of IN in the WHERE clause:
FOR EXAMPLE:
WHERE product_id = (1,2,3);
COUNT( posts.solved_post ) AS solved_post,
(SELECT users.username AS posted_by,
users.id AS posted_by_id
FROM users
WHERE users.id = posts.posted_by)
Well, you can’t get multiple columns from one subquery like that. Luckily, the second column is already posts.posted_by! So:
SELECT
topics.id,
topics.name,
topics.post_count,
topics.view_count,
posts.posted_by
COUNT( posts.solved_post ) AS solved_post,
(SELECT users.username AS posted_by_username
FROM users
WHERE users.id = posts.posted_by)
...
I got this error while executing a MySQL script in an Intellij console, because of adding brackets in the wrong place:
WRONG:
SELECT user.id
FROM user
WHERE id IN (:ids); # Do not put brackets around list argument
RIGHT:
SELECT user.id
FROM user
WHERE id IN :ids; # No brackets is correct
This error can also occur if you accidentally miss if function name.
for example:
set v_filter_value = 100;
select
f_id,
f_sale_value
from
t_seller
where
f_id = 5
and (v_filter_value <> 0, f_sale_value = v_filter_value, true);
Got this problem when I missed putting if in the if function!
Another place this error can happen in is assigning a value that has a comma outside of a string. For example:
SET totalvalue = (IFNULL(i.subtotal,0) + IFNULL(i.tax,0),0)
(SELECT users.username AS posted_by,
users.id AS posted_by_id
FROM users
WHERE users.id = posts.posted_by)
Here you using sub-query but this sub-query must return only one column.
Separate it otherwise it will shows error.
I also have the same issue in making a company database.
this is the code
SELECT FNAME,DNO FROM EMP
WHERE SALARY IN (SELECT MAX(SALARY), DNO
FROM EMP GROUP BY DNO);