I have two tables:
Table 1: Content [title, description, url, genre_id]
Table 2: Genre [genre_id, genre_name]
I'm trying to run a FULL SEARCH query so that if someone searches for a genre, the details from the Content will be returned. Equally if someone searches for a title, the Content will be returned as normal. Note that some Contents do not have a genre assigned so it will need to work in this scenario.
This is my query - I just can't work out how to get it working...
"SELECT content.*, genre.* FROM content LEFT OUTER JOIN genre
ON (genre.genre_id=content.genre_id)
WHERE MATCH (content.title, content.description)
AGAINST ('$query')
OR MATCH (genre.genre_name)
AGAINST ('$query')
AND content.url IS NOT NULL AND content.url <> '' LIMIT $lowerlimit, 10";
If you have Content items that don't have genre_id's, then INNER JOIN is not the way to go. That will exclude any Content items that don't have genre-id's. Use a LEFT OUTER JOIN instead. This assumes that there are no Genres whose genre_id's don't have a corresponding Content item. If the latter is the case, you need to create some kind of dummy row in your Content table to handle this. If this doesn't make sense, let me know and I'll give you more detail.
I am not familiarized with the WHERE MATCH ** AGAINST **, but I believe it could be rewritten to:
SELECT content.*, genre.*
FROM content
LEFT OUTER JOIN genre
ON genre.genre_id = content.genre_id
WHERE (content.title LIKE '%' + '$query' + '%'
OR content.description LIKE '%' + '$query' + '%'
OR genre.genre_name LIKE '%' + '$query' + '%')
AND content.url IS NOT NULL
AND content.url <> ''
LIMIT $lowerlimit, 10;
I also noted in your query there's a additional double quote at the end, before the semicolon.
Related
Say I have the below 2 tables:
text
id
text_lang
id
media_id
lang
text
(these are not the actual table structures - but I just have 2 tables with one containing all the localized strings that "belong" to the first table)
I want to join the tables, with a "preferred" language. So basically:
SELECT text.id, text_lang.text
FROM text
LEFT JOIN text_lang ON text.id = text_lang.text_id
AND (only a single row, and if there's a row with lang="en", pick that,
otherwise just pick any language)
The part I'm having trouble with is the "only a single row, and if there's a row with lang="en" pick that, otherwise just pick any language".
I think this does what I'm looking for:
SELECT text.id, text_lang.text
FROM text
JOIN text_lang ON text_lang.text_id = text.id AND
text_lang.lang = (select lang
FROM text_lang sub_text_lang
WHERE sub_text_lang.text_id = text.id
ORDER BY text_lang.lang = "en" DESC
limit 1)
... but I'd like to avoid a sub-query if possible, as I assume that would be quite a hit to the query performance.
I can think of a few ways but since you're trying to avoid subquery, perhaps you can do something like this:
SELECT t.id,
SUBSTRING_INDEX(
GROUP_CONCAT(text ORDER BY CASE WHEN lang='en' THEN 0 ELSE RAND() END),',',1)
AS extracted_text
FROM
text t
LEFT JOIN text_lang tl ON tl.text_id=t.id
GROUP BY t.id;
Use GROUP_CONCAT() with a customized ORDER BY then use SUBTRING_INDEX() to get the first value using comma (the default GROUP_CONCAT() separator) as the delimiter.
I've made a fiddle with sample data here: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=0d0501f36af1ba4e181856f761dbd5f7 . You can run the fiddle a few times to see that the text value other than 'en' change.
I'm new to SQL and I'm trying to make a basic query work.
This is the table and it's layout that I'm trying to search against:
https://prnt.sc/20wj54g
What I'm aiming to do is have a search term input, then have the input be used to search for names in the database by fullname.
This is the current query I have now:
SELECT *
FROM personnel p
LEFT JOIN department d ON (d.id = p.departmentID)
LEFT JOIN location l ON (l.id = d.locationID)
WHERE p.firstName LIKE '%Robert Heffron%' OR p.lastName LIKE '%Robert Heffron%';
This doesn't work as there is no last or firstname which contains the whole string "Robert Heffron" however this means if the user typed in that string looking for that person by the full name they wouldn't find them.
I'm currently using PHP and JS to display the data but I'm struggling with the SQL part.
If anyone could help I'd be very grateful.
This is not a good solution for performance, but if you want to solve the problem only using SQL, you can try this:
SELECT *
FROM personnel p
LEFT JOIN department d ON (d.id = p.departmentID)
LEFT JOIN location l ON (l.id = d.locationID)
WHERE LOWER(CONCAT(p.firstName, p.lastName)) LIKE LOWER(REPLACE('%Robert Heffron%', ' ', '%'))
OR LOWER(CONCAT(p.lastName, p.firstName)) LIKE LOWER(REPLACE('%Robert Heffron%', ' ', '%'));
Field concatenation is used to find a concatenated input value, and different combinations of OR concatenation are used to be independent of the order in which the first and last name are entered. Convert to lowercase - for case insensitive searches. We replace spaces with a % character to search for concatenated field values without worrying about spaces.
I would suggest adding a full name field to your database table and whenever you create a "personnel" in your code, you concatenate the first and last name:
Fullname = Firstname + " " + Lastname
if you don't like this, maybe use a string split function (in php it might be .explode()) and then adding WHERE OR statements for each substring for first and last name.
Use the following combination to find people whose name is Robert and whose last name is Heffron
Just find Robert Heffron
WHERE p.firstName LIKE '%Robert%' AND p.lastName LIKE '%Heffron%';
find all first names that have Robert and all last names that have Heffron
WHERE p.firstName LIKE '%Robert%' OR p.lastName LIKE '%Heffron%';
A solution that wouldn't ask you to change the table and having only one input variable could be something like this:
DECLARE #FullName AS VARCHAR(100)
SET #FullName = 'Robert Heffron'
SET #FullName = REPLACE(#FullName, ' ', '.')
SELECT....
WHERE p.firstname LIKE '%'+ ParseName(#FullName, 2) + '%' OR
p.firstname LIKE '%'+ ParseName(#FullName, 1) + '%' OR
p.lastnameLIKE '%'+ ParseName(#FullName, 2) + '%' OR
p.lastname LIKE '%'+ ParseName(#FullName, 1) + '%'
Downside in my opinion is if the user enters weird amount of spaces in the name. I have tested replacing the array number 1 or 2 in the ParseName with a number which was impossible, like 7, and it basically just ignores it.. no errors thrown or whatever. If you use this, you could test it on your side just to make sure tho.
You can use concat for the columns and can use "HAVING" clause on the concatenated column. I hope it will work for you.
SELECT * FROM personnel p LEFT JOIN department d ON (d.id = p.departmentID) LEFT JOIN location l ON (l.id = d.locationID) HAVING CONCAT(firstName,' ',lastName) LIKE '%Robert Heffron%';
I hope this snippet will work for you.
ok this is hard to explain...
i have the following tables:
table : words
table: word_progress
table: word_set
foreign keys:
words.id = word_set.word_id
word_progress.word_id = words.id
word_progress.user_id = users.id
basically a word is in a word_set. word_progress (it keeps score on a certain word) relates to a user_id and word_id.
the problem is sometimes there is not an entry in word_progress for user_id and word_id. but when it IS there, i wanna be able to use word_progress in the WHERE part of the query. but if it is not there I dont. My work around at the moment is before running the statement, i do an "insert IGNORE IF EXISTS into work_progress (word_id,user_id) values (?,?)" to make sure its there
i have this query
select
words.* ,
word_progress.progress from words
left join word_progress on word_progress.word_id = words.id
left join word_set on word_set.id = words.word_set_id
where word_set.id = ? and word_progress.user_id = ?
but... the problem is sometimes there is no word_progress entry for that word
how can i do this?
you're already left-joining, so when there's no data available, you'll just get null as value for your word_progress-fields. just check for that like this:
...
and
(
word_progress.user_id is null
or
word_progress.user_id = ?
)
another way would be to add the user-restriction directly to the join-criteria like this:
...
left join word_progress
on word_progress.word_id = words.id
and word_progress.user_id = ?
...
and drop that criteria from the where-part.
note that, in both cases, you'll have to handle the null-cases for progress later in your code properly.
yeah, this is ambiguous: " i wanna be able to use word_progress in the WHERE part of the query. but if it is not there I dont. "
in the left joins,
if there's no word_progress to match a word, you'll still get a result row for the word, it's just that all the fields of word_progress will be null.
Same for word_set: no corresponding word_set, then word_set.id and all the rest are null.
so include 'is null' or 'is not null' in your where clause depending on what you want.... think about that case, that's what you left ambiguous. or remember that 'a = b' is false if either a or b is null (even if they're both null), so design your where clause to fit.
I currently have a search form which should allow a user to search for a customers full name and it will return the row.
For Example: A user searches for "Mr. N Mallow" and it will return the row which matches that query. Since I am new to MySQL I need some help, I've tried + but that has no effect, probably because it's not standard mysql or something like that.
select *
from mooring
left join customer
on mooring.assignedTo = customer.id
where mooring.Number like \"$var\"
or (customer.TitleName + customer.Surname = '$var')
Any suggestions?
select * from mooring
left join customer on mooring.assignedTo = customer.id
where mooring.Number like \"$var\" OR (customer.TitleName + customer.Surname = '$var')
Try CONCAT_WS or CONCAT, which join strings together (the first version is "with separator"):
CONCAT(customer.TitleName,' ',customer.Surname)
or
CONCAT_WS(' ',customer.TitleName,customer.Surname)
i have one query that need some changes, and i don't get any clue to do this :
this is my query :
select * from user_data a
left join user_group b
on (a.role like b.role)
actually role value in userdata is (varchar)'staff'
and role value in group is (varchar)'staff;security;finance'
so i don't get result what i expected ..
i imagine the query should be similar to this :
select * from user_data a
left join user_group b
on (b.role like a.role+";%") // using wildcard
and i still don't know the right query using wildcard to this case
any one can help?
You can use CONCAT:
select * from user_data a
left join user_group b
on (b.role like CONCAT(a.role,";%")) // using wildcard
Note - does b.role only have to match a.role at the beginning? what if it was security;staff;finance? You could do CONCAT('%',a.role,'%').
You could do CONCAT('%','a.role','%') to handle matching a.role at any position, but only if you can be sure that you won't have nested roles.
For example: if b.role is staff and a.role is finance;gardenstaff;security, then this row will be returned from the query even though the role is gardenstaff and not staff.
As an alternative, you can use RLIKE instead of LIKE. This is basically a regular-expressions verson of LIKE.
In particular, the regex [[:<:]]staff[[:>:]] will match the whole word staff. The [[:<:]] and [[:>:]] stand for word boundaries, which stop you from matching the staff in gardenstaff.
So, your query could be:
select * from user_data a
left join user_group b
on (b.role RLIKE CONCAT('[[:<:]]',a.role,'[[:>:]]'))
And this would work for b.role being anywhere in the semicolon-separated a.role.