I have a form and MySQL that works with this:
$sql = "
SELECT p.*
, t.*, f.name AS fname
FROM table_posts p
JOIN table_topics t
USING(tid)
JOIN table_forums f
ON f.fid = t.fid
WHERE f.fid IN($forums)";
I wish to add an option on the form so that any tid's in the subscriptions table for the user are excluded from the results from the sql above:
$sql .= " LEFT JOIN (SELECT x.tid FROM table_subscriptions AS x WHERE x.username = '$user' AND x.type = 'x' GROUP BY x.tid) AS query2 USING (tid) AND query2.tid IS NULL";
however, am encountering
MySQL encountered 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 'LEFT JOIN (
Is the issue because the left join should be done first, or is there some other issue? Any clues for corrections appreciated.
You can bring in the subscriptions table with a LEFT JOIN, and then filter on unmatched records in the WHERE clause
SELECT
p.*,
t.*,
f.name AS fname
FROM table_posts AS p
INNER JOIN table_topics AS t USING (tid)
INNER JOIN table_forums AS f ON f.fid = t.fid
LEFT JOIN table_subscriptions AS s ON s.username = ? AND s.type = 'x' AND s.tid = p.tid
WHERE
f.fid IN (?, ?, ?)
AND s.tid IS NULL
Note: I updated your query so it uses query parameters instead of concatenating variables in the SQL string: this is both more efficient and secure.
You can also use NOT EXISTS:
SELECT
p.*,
t.*,
f.name AS fname "
FROM table_posts AS p
INNER JOIN table_topics AS t USING (tid)
INNER JOIN table_forums AS f ON f.fid = t.fid
WHERE NOT EXISTS (
SELECT 1
FROM table_subscriptions AS s
WHERE s.username = ? AND s.type = 'x' AND s.tid = p.tid
)
WHERE f.fid IN (?, ?, ?)
Related
I am using the expression below to find out which 'resource' type customers have 'work_resource' that are active.
WITH cte_ss AS (SELECT wr.user_id
FROM work w
JOIN work_resource wr ON wr.work_id = w.id
WHERE wr.work_resource_status_type_code = 'active'
),
SELECT u.uuid
FROM user u
JOIN company c ON c.id = u.company_id
LEFT JOIN cte_ss on cte_ss.user_id = u.id
AND c.customer_type = 'resource'
White trying to run this, 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 'SELECT u.uuid
FROM user u
JOIN company c ON c.id = u.company_id
LEFT JOIN cte_ss' at line 6
Both the individual queries (without the LEFT JOIN) are working, so not sure what I am doing wrong here
A cte would look like this
But as i don't know nothing about your tables, you have to figure it out yourself
WITH cte_ss AS (
SELECT
user_id
FROM work w
JOIN work_resource wr ON wr.work_id = w.id
WHERE wr.work_resource_status_type_code = 'active'
)
SELECT u.uuid
FROM user u
JOIN company c ON c.id = u.company_id
LEFT JOIN cte_ss on cte_ss.user_id = u.id
AND c.customer_type = 'resource'
I've just started learning SQL. Here is part of my Database:
I want to get the project name from the Project table with condition:
name = 'turbine' and value = '03' in Parameter table.
I have wrote the following query and it seems to work!
But I was wondering if any smarter query can do the job for me :
SELECT name
FROM Project
WHERE id IN (
SELECT projectId
FROM Cases
WHERE id IN (
SELECT caseId
FROM ParamValue
WHERE parameterId IN (SELECT id FROM Parameter WHERE name = 'turbine')
AND value = '03')
)
;
Instead of several nested IN clause with subquery seems more easy to read a proper set of inner join
select distinct Project.name
from Project
INNER JOIN Cases ON Cases.projectId = Project.id
INNER JOIN ParamValue ON ParamValue.caseId = Cases.id
AND ParamValue.value ='03'
INNER JOIN Parameter ON ParamValue.parameterId = Parameter.id
AND Parameter.name = 'turbine'
Sure here you go without subqueries:
SELECT pj.Name
FROM Parameter p
INNER JOIN ParamValue pv ON pv.Value = '03' AND p.Id = pv.parameterId
INNER JOIN Cases c ON pv.caseId = c.Id
INNER JOIN Project pj ON c.projectId = pj.Id
WHERE p.name = 'turbine'
;
select pr.name from Project pr
left join Cases c on pr.name = c.id
left join ParamValue pv on c.id = pv.parameterId
left join Parameter p on p.id = pv.parameterId
where p.name = 'turbine' and pv.value = '03';
I've got the following SQL query and I'm trying to implement pagination, so I first want to get the COUNT of the result:
The normal query (works fine)
SELECT DISTINCT c.*, p1.*, username FROM candidate c
LEFT JOIN note p1 ON (c.candID = p1.candidateID)
LEFT JOIN user ON p1.userID = user.id
LEFT OUTER JOIN note p2 ON
(c.candID = p2.candidateID AND (p1.noteID < p2.noteID))
WHERE p2.candidateID IS NULL ORDER BY c.firstname ASC
I've tried the following, but it throws an error and I'm not sure what correct syntax to use:
Attempting to count the results (doesn't work)
SELECT COUNT(DISTINCT c.*, p1.*, username) FROM candidate c
LEFT JOIN note p1 ON (c.candID = p1.candidateID)
LEFT JOIN user ON p1.userID = user.id
LEFT OUTER JOIN note p2 ON
(c.candID = p2.candidateID AND (p1.noteID < p2.noteID))
WHERE p2.candidateID IS NULL ORDER BY c.firstname ASC
The error:
Syntax error or access violation: 1064 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 ', p1., username) FROM candidate c LEFT ' at line 1
One option is to use a subquery:
SELECT COUNT(*)
FROM (
SELECT DISTINCT c.*, p1.*, username FROM candidate c
LEFT JOIN note p1 ON (c.candID = p1.candidateID)
LEFT JOIN user ON p1.userID = user.id
LEFT OUTER JOIN note p2 ON
(c.candID = p2.candidateID AND (p1.noteID < p2.noteID))
WHERE p2.candidateID IS NULL
) t
Depending on your data, you may be able to do this without the subquery, but you cannot use multiple columns with the count aggregate -- that's what is causing your error.
I have three tables A B C and i'm trying to retrieve information from all three.
A has the columnns userid avatar username and B has the column postid, dateshared and C has the column commenter postid datecommented.
I'm trying to run the query
Select C.comment, C.commenter, C.datecommented, B.postid, B.dateshared A.username A.avatar from B Left Join C Left join A on C.postid = B.postid AND A.userid = C.commenter where B.postid IN ('1','2','3') order by C.dateshared desc
but it gives 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 'where B.postid IN ('1', '2', '3') order by C.dateshared '
Can anyone point out what I'm doing wrong or suggest how to go about it?
Each LEFT JOIN requires its own ON condition:
SELECT C.comment, C.commenter, C.datecommented, B.postid, B.dateshared, A.username A.avatar
FROM B
LEFT JOIN
C
ON C.postid = B.postid
LEFT JOIN
A
ON A.userid = C.commenter
WHERE B.postid IN ('1','2','3')
ORDER BY
C.dateshared desc
This should work for you, your query had some syntax errors:
Select C.comment,C.commenter,C.datecommented,B.postid,B.dateshared,A.username,A.avatar
from B
Left Join C on C.postid = B.postid
Left join A on A.userid = C.commenter
where B.postid IN ('1','2','3')
order by C.dateshared desc
In my Yii application, I have following database structure:
Table user (id, firstName, lastName)
Table category (id, categoryName)
Table item (id, categoryId, name)
Table usergroup(id, userId, groupName)
I am trying to run following query:
$sql = 'SELECT a.id, a.firstName, a.lastName, b.id, b.categoryName, c.id, c.name
FROM user AS a
INNER JOIN (category AS b ON a.id = b.userId
WHERE b.userId IN (SELECT f.id FROM usergroup f WHERE f.userId=:currentUserId))
INNER JOIN item AS c ON b.id = c.categoryId
WHERE c.name LIKE :listedName';
$command=$connection->createCommand($sql);
$currentUserId = Yii::app()->user->id;
//binding :currentUserId
$command->bindParam(":currentUserId", $currentUserId,PDO::PARAM_STR);
$listedItemName = $data->name;
//binding :listedItemName
$command->bindParam(":listedName", $listedName,PDO::PARAM_STR);
$dataReader=$command->query();
However, I get following excption:
CDbException
CDbCommand failed to execute the SQL statement: SQLSTATE[42000]:
Syntax error or access violation: 1064 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 'ON a.id = b.userId WHERE b.userId IN
(SELECT f.id FROM usergroup' at line 3.
The SQL statement executed was:
SELECT a.id, a.firstName, a.lastName, b.id, b.categoryName, c.id, c.name FROM user AS a INNER JOIN (category AS b ON a.id = b.userId WHERE b.userId IN (SELECT f.id FROM usergroup f WHERE f.userId=:currentUserId)) INNER JOIN item AS c ON b.id = c.categoryId WHERE c.name LIKE :listedName. Bound with :currentUserId='2', :listedName='Oliver Twist'
Any sort of help or advice will be highly appreciated. Thank You!
You seem to have some parenthesis issue in there as well as possibly an unnecessary sub-select. I am guessing that what you are looking for is:
SELECT a.id, a.firstName, a.lastName, b.id, b.categoryName, c.id, c.name
FROM user AS a
INNER JOIN category AS b ON a.id = b.userId
INNER JOIN usergroup AS f ON f.userID = a.id
INNER JOIN item AS c ON b.id = c.categoryId
WHERE c.name LIKE :listedName'
AND f.userID=:currentUserId;
But, I am unclear on the join between item and category tables. You don't seem to to have foreign for category in items table and are just joining the item id and category id.
I am also unclear on your join between the user table and category table where you are saying the user id = category id. I don't see how these are related.
For update/reference of any one else facing same issue. I later figured out the problem that SQL WHERE CLAUSE should only be used at the end of statement, and I changed the first WHERE clause with AND condition. Here is the working query:
$sql = 'SELECT a.id, a.firstName, a.lastName, b.id, b.categoryName, c.id, c.name
FROM user AS a
INNER JOIN (category AS b ON a.id = b.userId
AND b.userId IN (SELECT f.id FROM usergroup f WHERE f.userId=:currentUserId))
INNER JOIN item AS c ON b.id = c.categoryId
WHERE c.name LIKE :listedName';