Two tables:
prefix ( id, value )
---------------------
1 'hello'
2 'good afternoon'
3 'good night'
suffix ( id, value )
---------------------
1 'world'
3 'world'
I'd like to get
all from table prefix which can be joined on table suffix via id
result should look like:
prefix.id prefix.value
--------------------------
1 'hello'
3 'good night'
well - quite easy so far...
but if table suffix is empty I'd like everything from table prefix
without subselects/ctes or if.... and in one query fulfilling both conditions!
Is there any trick to get this done by some magic having-clause or tricky something else?
Just for testcases: SQL-fiddle
Well, there is a way, but I agree with others that your requirements make no (practical) sense.
Anyway, here you go:
Join the suffix table twice (each time with a left join). One join is on the id column, the other on an always true condition.
Group the results on the prefix columns you want in the output and at least one non-nullable column of the first instance of suffix.
In the HAVING clause, put a condition that the first suffix column is not null or the number of values of a non-nullable column in the second suffix instance is 0. (Obviously, every group will have the same number of rows, i.e. the count will be the same for every prefix row.)
This is the query:
SELECT prefix.id, prefix.value
FROM prefix
LEFT JOIN suffix ON prefix.id = suffix.id
LEFT JOIN suffix AS test ON 1=1
GROUP BY prefix.id, prefix.value, suffix.id
HAVING suffix.id IS NOT NULL OR COUNT(test.id) = 0;
And there's also a demo at SQL Fiddle.
You need an OR and NOT EXISTS:
SELECT
prefix.id, prefix.value
FROM
prefix
WHERE
EXISTS(SELECT 1 from suffix WHERE prefix.id=suffix.id)
OR NOT EXISTS(SELECT 1 FROM suffix)
Demo
I guess the answer is: no, you can't!
Or if you can: No, you shouldn't.
Related
id name redirect_id
1 .... NULL
2 ..... NULL
3 ..... 2
4 .... NULL
5 .... 1
i have this table. id is primary key. I want to get name of the row. However if it has a redirect_id, i want to get redirected id's name. Is there a possible way to do it in one sql query?
I know how to do it after fetching the result array. However it becomes so tangled if i do it that way. 1 sql query would be so good here. Thanks.
edit i need all redirected row not just redirrected name.
select ln.id
, COALESCE(ln2.name, ln.name)
from linkednames ln
left join linkednames ln2 on ln2.id = ln.redirect_id
If there is only one hop, then this is a simple join:
select t.id, (case when t.redirect_id is null then t.name else tr.name end) as name
from t left join
t tr
on t.redirect_id = tr.id;
If re-directs can have re-directs, you'll need more joins. MySQL does not have good support for hierarchical/recursive queries.
I have the following doubt about this simple INNER JOIN query.
I have these two tables that have to be joined togheter:
The first table is named VulnerabilityFix and contains the following columns:
Id: int identity
FixName: varchar
Vendor: varchar
Title: varchar
Version: varchar
The second table is named VulnerabilityAlertDocument_VulnerabilityFix (this bind the previous table to another table, but this is not important at this time) and contains the following columns:
VulnerabilityAlertDocumentId: int
VulnerabilityFixId: int
Now, on my DB the VulnerabilityFix table contains only an empty record (this record have an id but all the other fields are empty\null), infact if I perform a select *, I obtain:
select * from VulnerabilityFix
Id FixName Vendor Title Version
1
Into the VulnerabilityAlertDocument_VulnerabilityFix I have something like this:
select * from VulnerabilityAlertDocument_VulnerabilityFix
VulnerabilityAlertDocumentId VulnerabilityFixId
78385 1
78386 1
....................................................
....................................................
....................................................
78398 1
Ok, so I want JOIN toghert these 2 table in in such a way that passing the value of the VulnerabilityAlertDocumentId field of the VulnerabilityAlertDocument_VulnerabilityFix table, I obtain all the related record in the VulnerabilityFix table.
So in this case I aspect to retrieve the previous only record that having an id (having a value equal to 1) and all the other fields are empty\null.
So my query is:
SELECT VF.* FROM VulnerabilityAlertDocument_VulnerabilityFix VAD_VF
INNER JOIN VulnerabilityFix VF ON VAD_VF.VulnerabilityAlertDocumentId = VF.Id
WHERE VAD_VF.VulnerabilityAlertDocumentId = 1
The problem is that when I execute this query I obtain an empty set of records and not the unique record that I expetc to obtain.
Why? What am I missing?
Tnx
I think your query should be more like:
SELECT VF.* FROM VulnerabilityAlertDocument_VulnerabilityFix VAD_VF
INNER JOIN VulnerabilityFix VF ON VAD_VF.VulnerabilityFixId = VF.Id
WHERE VAD_VF.VulnerabilityAlertDocumentId = 78385
That is, you are using the wrong column at your ON condition since VulnerabilityFixId seems to be the foreign key over VulnerabilityFix.Id and not VulnerabilityAlertDocumentId.
On the other hand, I can't see any VulnerabilityAlertDocument_VulnerabilityFix.VulnerabilityAlertDocumentId with value 1 in you data set (where condition)
I would like to write a query to pick out rows with the same cottageid, from, and to values, so in this case it would pick out the rows with the id 991, and 992. The table name is datesBooked.
You can join the table with itself:
select d1.id,d2.id from datesBooked d1
inner join datesBooked d2 on
d1.cottageid=d2.cottageid
and d1.from = d2.from
and d1.to = d2.to
and d1.id<d2.id
That would give you the duplicates. I am only getting the ones that have lesser id than the following one (that way you will get the duplicates in the right column, and the originals in the first one)
Try this:
SELECT * FROM datesBooked
GROUP BY cottageid, from, to
HAVING COUNT(cottageid) > 1
I used a Java method called 'containsAll()' to check if ArrayLists have common content.
Let's say I have a list A (one row), and several other lists in a MySQL table (in column 'name', row by row).
All lists consist of comma-separated Strings (at least one String in a list) - names or whatever.
Now, I want to check if all Strings in list A can be found in any of the rows in column 'name'.
The result set should show all the rows in 'name' that match, that includes rows/lists must have all Strings in list A, and can have additional Strings.
Example I
A: 'Mr.T'
____name_________________________________________
'Hannibal'
'Hannibal','Face','Murdock','Mr.T','Donald Duck'
'Face','Donald Duck'
'Superman','Chuck Norris','Mr.T'
_________________________________________________
Result set: 'Hannibal','Face','Murdock','Mr.T','Donald Duck' -AND-
'Superman',Chuck Norris','Mr.T'
Example II
A: 'Rocky', 'Mr.T', 'Apollo'
______name__________________________________________________
'Hannibal','Face','Murdock','Donald Duck','Superman','Mr.T'
'Rocky','Apollo','Ivan'
'Apollo', 'Superman','Hannibal','Rocky','Mr.T','Chuck Norris'
'Rocky','Mr.T','Apollo','Chuck Norris'
_____________________________________________________________
Result set: 'Apollo', 'Superman','Hannibal','Rocky','Mr.T','Chuck Norris' -AND-
'Rocky','Mr.T','Apollo','Cuck Norris'
I wonder if one can carry out those results using a MySQL query.
Thank you in advance.
It appears you want to do an array intersection, except your array is a single column. It can be done, but it will be slow, difficult to debug and will not leverage the power of relational databases. A better way would be to change your table schema to something like this:
Table groups
group_id int unsigned not null auto_increment primary key,
character_list text
Table members_in_group
group_id int unsigned not null,
group_member varchar(45) not null
Then you can query like this:
SELECT group_id, character_list
FROM groups g
JOIN members_in_groups m USING (group_id)
WHERE m.group_member IN ('Mr. T', ...);
The groups table is probably very like your current table. The members_in_groups table is the same data chopped up into easily searchable parts.
ETA given your comment, this should work if you can guarantee that each character_list contains only one instance of each character:
SELECT group_id,
SUM(CASE m.group_member IN ('Mr. T', 'Apollo', 'Rocky') THEN 1 ELSE 0 END) AS tally,
character_list
FROM groups g
JOIN members_in_groups m ON (g.group_id=m.group_id)
GROUP BY group_id
HAVING SUM(CASE m.group_member IN ('Mr. T', 'Apollo', 'Rocky') THEN 1 ELSE 0 END) = 3;
In this case the HAVING clause must equal 3 because there are 3 members in IN ('Mr. T', 'Apollo', 'Rocky').
I solved this issue by using the REGEXP function in MySQL:
SELECT * FROM `table` WHERE `column` REGEXP("(value1|value2|value3)");
SELECT * FROM tbl_name WHERE field_name LIKE '%\'Mr.T\'%'
I'd like to use a single SQL query (in MySQL) to find the record which comes after one that I specify.
I.e., if the table has:
id, fruit
-- -----
1 apples
2 pears
3 oranges
I'd like to be able to do a query like:
SELECT * FROM table where previous_record has id=1 order by id;
(clearly that's not real SQL syntax, I'm just using pseudo-SQL to illustrate what I'm trying to achieve)
which would return:
2, pears
My current solution is just to fetch all the records, and look through them in PHP, but that's slower than I'd like. Is there a quicker way to do it?
I'd be happy with something that returned two rows -- i.e. the one with the specified value and the following row.
EDIT: Sorry, my question was badly worded. Unfortunately, my definition of "next" is not based on ID, but on alphabetical order of fruit name. Hence, my example above is wrong, and should return oranges, as it comes alphabetically next after apples. Is there a way to do the comparison on strings instead of ids?
After the question's edit and the simplification below, we can change it to
SELECT id FROM table WHERE fruit > 'apples' ORDER BY fruit LIMIT 1
SELECT * FROM table WHERE id > 1 ORDER BY id LIMIT 1
Even simpler
UPDATE:
SELECT * FROM table WHERE fruit > 'apples' ORDER BY fruit LIMIT 1
So simple, and no gymnastics required
Select * from Table
where id =
(Select Max(id) from Table
where id < #Id)
or, based on the string #fruitName = 'apples', or 'oranges' etc...
Select * from Table
where id =
(Select Max(id) from Table
where id < (Select id from Table
Where fruit = #fruitName))
I'm not familiar with the MySQL syntax, but with SQL Server you can do something with "top", for example:
SELECT TOP 1 * FROM table WHERE id > 1 ORDER BY id;
This assumes that the id field is unique. If it is not unique (say, a foreign key), you can do something similar and then join back against the same table.
Since I don't use MySQL, I am not sure of the syntax, but would imagine it to be similar.
Unless you specify a sort order, I don't believe the concepts of "previous" or "next" are available to you in SQL. You aren't guaranteed a particular order by the RDBMS by default. If you can sort by some column into ascending or descending order that's another matter.
This should work. The string 'apples' will need to be a parameter.
Fill in that parameter with a string, and this query will return the entire record for the first fruit after that item, in alphabetical order.
Unlike the LIMIT 1 approach, this should be platform-independent.
--STEP THREE: Get the full record w/the ID we found in step 2
select *
from
fruits fr
,(
--STEP TWO: Get the ID # of the name we found in step 1
select
min(vendor_id) min_id
from
fruits fr1
,(
--STEP ONE: Get the next name after "apples"
select min(name) next_name
from fruits frx
where frx.name > 'apples'
) minval
where fr1.name = minval.next_name
) x
where fr.vendor_id = x.min_id;
The equivalent to the LIMIT 1 approach in Oracle (just for reference) would be this:
select *
from
(
select *
from fruits frx
where frx.name > 'apples'
order by name
)
where rownum = 1
I don't know MySQL SQL but I still try
select n.id
from fruit n
, fruit p
where n.id = p.id + 1;
edit:
select n.id, n.fruitname
from fruits n
, fruits p
where n.id = p.id + 1;
edit two:
Jason Lepack has said that that doesn't work when there are gaps and that is true and I should read the question better.
I should have used analytics to sort the results on fruitname
select id
, fruitname
, lead(id) over (order by fruitname) id_next
, lead(fruitname) over (order by fruitname) fruitname_next
from fruits;
If you are using MS SQL Server 2008 (not sure if available for previous versions)...
In the event that you are trying to find the next record and you do not have a unique ID to reference in an applicable manner, try using ROW_NUMBER(). See this link
Depending on how savvy your T-SQL skill is, you can create row numbers based on your sorting order. Then you can find more than just the previous and next record. Utilize it in views or sub-queries to find another record relative to the current record's row number.
SELECT cur.id as id, nxt.id as nextId, prev.id as prevId FROM video as cur
LEFT JOIN video as nxt ON nxt.id > cur.id
LEFT JOIN video as prev ON prev.id < cur.id
WHERE cur.id = 12
ORDER BY prev.id DESC, nxt.id ASC
LIMIT 1
If you want the item with previous and next item this query lets you do just that.
This also allows You to have gaps in the data!
How about this:
Select * from table where id = 1 + 1