SELECT ids_horarios_adicionales from adicionales WHERE id_adicionales=1
So this query returns as result 1,3, the row ids_horarios_adicionales will contain ids separated with commas.
What im intending to do is this:
SELECT *
FROM adicionales a
LEFT JOIN horarios b ON b.id_horarios IN (1,3)
WHERE id_adicionales=1
but when I use this query, results are not the same:
SELECT *
FROM adicionales a
LEFT JOIN horarios b ON b.id_horarios IN (SELECT ids_horarios_adicionales from adicionales WHERE id_adicionales=1)
WHERE id_adicionales=1
any idea how to make SELECT query inside IN() to print as 1,3
This is the schema and sql query result I want, any other approach sugested will be helpful: http://sqlfiddle.com/#!9/714a50/2
You should not be storing values in a comma-separated list. That is the problem you are facing. I would recommend figuring out how to change your data structure.
But, sometimes, you are stuck with other people's really bad designs (such as storing integer values in strings). In that case, you can use find_in_set():
SELECT *
FROM adicionales a LEFT JOIN
horarios h
ON EXISTS (SELECT 1
FROM adicionales a2
WHERE find_in_set(h.id_horarios , a2) > 0 AND
a2.id_adicionales = 1
)
WHERE id_adicionales = 1
you can use FIND_IN_SET by this way
SELECT *
FROM adicionales a
LEFT JOIN horarios b ON
FIND_IN_SET(a.ids_horarios_adicionales,b.id_horarios)
WHERE id_adicionales=1
I'm not sure of your schema but in general when using LEFT JOIN you need to detail how the join between the tables us done. For example, LEFT JOIN horarios b ON b.index = adicionales.index and then use the where statement to limit rows
Related
I have some problems with a MYSQL Query. I'm trying to do a LEFT JOIN with multiple parameters.
DB Structure:
A soldier can have more than one tag, these tags are assigned to the soldier with a ManyToMany relationship
My query is used in a search function where the user is able to add some tags he/she want to look for. So far its possible to search with one tag but as soon you add more than one tag, the query will not return an result even if it should.
Query used:
SELECT *
FROM soldiers s LEFT JOIN
soldier_tag st
ON s.id = st.soldier_id
WHERE st.tag_id = 5;
When the user enters 2 tags, then both tags should math. The query will become this:
SELECT *
FROM soldiers s LEFT JOIN
soldier_tag st
ON s.id = st.soldier_id
WHERE st.tag_id = 5 AND st.tag_id = 7;
Does anyone have an idea how I can fix this problem?
Thanks in advance
You will want to use 'IN' followed by the parameter as done below, this will consider both parameters when the query is executed.
SELECT *
FROM soldiers s LEFT JOIN
soldier_tag st
ON s.id = st.soldier_id
WHERE st.tag_id IN (5,7);
When a join condition is related to a set of values (eg a list of tag) You should use a in clause
SELECT *
FROM soldiers s
LEFT JOIN soldier_tag st ON s.id=st.soldier_id
WHERE st.tag_id in ( 5 , 7)
If you want all tags to match, I would suggest phrasing the query as something like this:
SELECT s.*
FROM soldiers s
WHERE s.id IN (SELECT st.soldier_id
FROM solder_tag st
WHERE st.tag_id IN (5, 7) -- construct an `IN` list instead of a bunch of boolean expressions
GROUP BY st.soldier_id
HAVING COUNT(*) = 2 -- 2 is the number of tags
);
The subquery returns the soldier_ids where all the tags match. You need to put the list in IN and the count in the HAVING clause.
You should use OR operator in your WHERE clause:
SELECT *
FROM soldiers s
LEFT JOIN soldier_tag st ON s.id=st.soldier_id
WHERE st.tag_id=5 OR st.tag_id=7
If it's possible to have more than 2 tags in query, it's better to use IN operator as #scaisEdge mentioned
I am working on a query with the following format:
I require all the columns from the Database 'A', while I only require the summed amount (sum(amount)) from the Database 'B'.
SELECT A.*, sum(B.CURTRXAM) as 'Current Transaction Amt'
FROM A
LEFT JOIN C
ON A.Schedule_Number = C.Schedule_Number
LEFT JOIN B
ON A.DOCNUMBR = B.DOCNUMBR
ON A.CUSTNMBR = B.CUSTNMBR
GROUP BY A
ORDER BY A.CUSTNMBR
My question is regarding the grouping statement, database A has about 12 columns and to group by each individually is tedious, is there a cleaner way to do this such as:
GROUP BY A
I am not sure if a simpler way exists as I am new to SQL, I have previously investigated GROUPING_ID statements but thats about it.
Any help on lumped methods of grouping would be helpful
Since the docnumber is the primary key - just use the following SQL:
SELECT A.*, sum(B.CURTRXAM) as 'Current Transaction Amt'
FROM A
LEFT JOIN C
ON A.Schedule_Number = C.Schedule_Number
LEFT JOIN B
ON A.DOCNUMBR = B.DOCNUMBR
ORDER BY RM20401.CUSTNMBR
GROUP BY A.DOCNUMBR
This is my query. The output looks fine except the COUNT function is returning numbers which seem totally arbitrary (e.g. 7-digit numbers where I'd expect 3-digit numbers):
SELECT tc.tableName, m.fieldName, COUNT(m.fieldName)
FROM apiResult, (
SELECT cc.surveyID, cc.fieldName
FROM apiResult as ar
INNER JOIN columnConversion as cc
ON substring(ar.triggerName,-10)=cc.fieldID
) AS m
INNER JOIN tableConversion as tc
ON m.surveyID=tc.surveyID
GROUP BY tc.tableName, m.fieldName;
I think, for a start, that COUNT(m.fieldName) is probably wrong, since it doesn't correspond with GROUP BY tc.tableName, m.fieldName.
Here's what the query is meant to do: one of the tables in the sub-query, apiResult, has a column called 'triggerName' which contains an ID I call 'fieldID', plus a column called 'surveyID'. The tables columnConversion and tableConversion are tables which match the IDs to human readble names. So, the follow query produces the count that I want, but, I want the IDs replaced by the human readable names, hence the above query:
SELECT cc.surveyID, cc.fieldName, COUNT(ar.triggerName)
FROM apiResult as ar
INNER JOIN columnConversion as cc
ON substring(ar.triggerName,-10)=cc.fieldID
GROUP BY (ar.triggerName)
Any ideas what I've done wrong?
Why are you mixing explicit and implicit joins? You appear to have missed a join condition on the first table. Well, actually, I don't think it is needed. This should work:
SELECT tc.tableName, m.fieldName, COUNT(m.fieldName)
FROM (SELECT cc.surveyID, cc.fieldName
FROM apiResult ar INNER JOIN
columnConversion cc
ON substring(ar.triggerName, -10) = cc.fieldID
) m INNER JOIN
tableConversion as tc
ON m.surveyID = tc.surveyID
GROUP BY tc.tableName, m.fieldName;
So after helpful feedback from my original question, I now have this query:
SELECT sessions.id, sessions.title, sessions.abstract, sessions.presenters, sessions.proposal_id, proposals.outcomes, proposals.CategorySelection, proposals.research3, proposals.research4, proposals.research5, proposals.research6, proposals.innovation3, proposals.innovation4, proposals.innovation5,proposals.innovation6, proposals.application3, proposals.application4, proposals.application5, proposals.application6, proposals.integration3, proposals.integration4, proposals.integration5, proposals.integration6, proposals.references, proposals.organization
FROM sessions, proposals
INNER JOIN proposals ON proposals.id = sessions.proposal_id
WHERE sessions.id = '$id
LIMIT 1;)
that is getting me nowhere fast. What am I doing wrong?
Original question:
I need to pull several fields from one table and several more from a second table. The criteria is that a field called proposal_id match the id field of the second table. I am fairly new so this is what I have so far. It is not working, but not sure how to make it work.
(SELECT `title`,`abstract`,`presenters`,`proposal_id` FROM `sessions` WHERE `id`='$id')
UNION
(SELECT `outcomes`,`CategorySelection`,`research3`,`research4`,`research5`,`research6`,`innovation3`,`innovation4`,`innovation5`,
`innovation6`,`application3`,`application4`,`application5`,`application6`,`integration3`,`integration4`,`integration5`,`integration6`,`references`,`organization` FROM `proposals` WHERE `id`= `sessions`.`proposal_id`)
LIMIT 1;
You need to use JOIN not UNION
select
s.*,p.*
from `sessions` s
inner join `proposals` p on p.id = s.proposal_id
where s.id = '$id'
This is how you can join both the tables using the common key between.
You can select the specific fields instead of .* by specifying the column names as
s.col1,s.col2,p.col1,p.col2
etc
Try to use JOINS, where you can match the related fields from both the tables , this is the most convenient way to fetch records from multiple tables
UNION is used when you want to combine two queries
select a.id,b.some_field from table1 as a
INNER JOIN table2 as b ON b.prospal_id = a.id
I have a select query which selects all products from my inventory table and joins them with two other tables (tables l_products and a_products)
SELECT
i.*,
b.title,
ROUND((i.price/100*80) - l.price,2) AS margin,
l.price AS l_price,
a.price AS a_price,
ROUND((a.price/100*80) - l.price, 2) AS l_margin
FROM inventory i
LEFT JOIN products b ON i.id = b.id
LEFT JOIN a_products a ON i.id = a.id
LEFT JOIN l_products l ON i.id = l.id
WHERE
a.condition LIKE IF(i.condition = 'New', 'New%', 'Used%')
AND l.condition LIKE IF(i.condition = 'New', 'New%', 'Used%')
This select query will normally give me a table such as...
id, title, condition, margin, l_price, a_price ...
001-new ... new 10 20 10
001-used ... used 10 25 20
002....
Now I need a condition in the query which will ignore all used products that are more expensive (have a higher a_price) than their 'new' counterparts, such as in the example above you can see that 001-used has a higher a_price than 001-new.
How can I achieve this with out having to resolve to using php
FULL JOIN this query with it self on a column which has a uniquely same value for each id prefix.
You may achieve this effect by adding another field to your SELECT call which produces same unique value for 001-new and 001-used, 002-new and 002-used...
Such value generation can be done by defining your own SQL Routine to extract first 3 characters from a column.