I have a query as follow: (shows are a table with tv shows and IMDB ID and recommended_titles is a table with two columns with IMDB_ID)
Select t2.* from shows t, shows t2, recommended_titles WHERE
t.imdb_id = recommended_titles. title_id_1
AND recommended_titles.title_id_2=t2.imdb_id
AND t.imdb_id = 0367279 LIMIT 7
The query is fine but I realized that it was only checking in the first column for my imdb id when it can also appear in my second one.
So i try to add the following:
OR
recommended_titles.title_id_2=t.imdb_id
AND t.imdb_id = recommended_titles. title_id_1
AND t.imdb_id = 0367279 LIMIT 7
But apparently OR can't be used with AND,
any suggestions as how I should do this ?
Edit:
To explain what I'm trying to do, here's a quick example in case my explanations above are too confusing.
table shows has rows like this:
name of a tv show | 00001
name of another | 00002
name of another | 00003
table recommended titles has (notice that an ID can be in either column)
00001 | 00002
00002 | 00003
You may look at operator precedence in mysql (and see that AND has an higher precedence than OR), or use parenthesis (much easier to use and maintain)
(t.imdb_id = recommended_titles.title_id_1 OR
recommended_titles.title_id_2=t.imdb_id)
AND recommended_titles.title_id_2=t2.imdb_id
AND t.imdb_id = 0367279 LIMIT 7
Do it like this,
(recommended_titles.title_id_2=t.imdb_id
OR t.imdb_id = recommended_titles. title_id_1)
AND t.imdb_id = 0367279 LIMIT 7
(t.imdb_id = recommended_titles. title_id_1
OR recommended_titles.title_id_2=t.imdb_id )
AND t.imdb_id = 0367279 LIMIT 7
Just use parenthesis to group your conditions for priorities.
Related
I don't know which way would be better for PHP and SQL.
I design and program my own comment system and I would like id2=0 its a comment and id2>0 its sub-comment in one table. This means that if someone wrote a sub-comment in a comment with ID=1, then ID2 is responsible for assigning (sub-comment) to ID=1 (comment).
I have one table comments like this:
id | id2 | smt | etc.
1 | 0 | x | x //comment with sub-comment where id=3
2 | 0 | x | x //comment
3 | 1 | x | x //that is sub-comment for comment where id=1
I'm displaying this in a while loop because I need to print all the data from comments. Like this:
$sqlkom="SELECT * FROM `comments` WHERE `id`='".$row['id']."' ORDER BY id DESC LIMIT 20";
if($resultkom = mysqli_query($con, $sqlkom)){
if(mysqli_num_rows($resultkom)){
while($rowkom = mysqli_fetch_assoc($resultkom)) {
echo HtmlFormatFunction($rowkom['id'],$rowkom['id2'],$rowkom['smt'],$rowkom['etc'])
I won't achieve this: if($rowkom['id']==$rowkom['id2']) without adding another while() loop, right?
or maybe it is enough to modify the SQL query to achieve this effect? Please, help me with the right solution.
You can join your table with itself, something like that:
SELECT c.id, c.id2, c.smt, c.etc,
s.id, AS s_id, s.id2 AS s_id2, s.smt AS s_smt, s.etc AS s_etc
FROM `comments` c LEFT JOIN `comments` s
ON c.id = s.id2
WHERE c.id = ?
ORDER BY c.id DESC LIMIT 20";
Then you should get minimum one line for the first comment or as much as lines for the first comment as there are sub-comments. Then the first four fields will repeat, but thats not an issue. Maybe this is not perfect. Hope you get the idea.
I wonder if someone could help me with an SQL query.
I am trying to display all results except where in Table 2 both the userid column equals 1 and the hidden column equals 1.
I am basically trying to hide results from individual users based on their id and the value in the hidden column either 1 or empty.
I have so far managed to make a query that does the opposite and can't figure out how to change it. I have tried adding !=, <>, NOT and a few other things, but nothing is working for me!
Here is the query I am working with.
$stmt = $conn->prepare("SELECT tl.id, tl.name, tl.locale, uh.hidden
FROM theList AS tl
LEFT JOIN user_hidden_list AS uh ON uh.est_id = tl.id
WHERE uh.userid = '1' AND uh.hidden = '1'");
How do I display all results expect those with a uh.userid = 1 and uh.hidden = 1
UPDATE: Tables
Table: user_hidden_list
userid | Hidden | est_id
---------------------------
1 | 1 | 1
2 | 1 | 1
1 | 1 | 2
Table: theList
id | name | locale
------------------------
1 | Jacks | LDN
2 | MacD's | LDN
3 | BK | LDN
4 | Byron | LDN
So if I am logged in with and userid of:
1 I should see: BK and Byron.
2 I should see: MacD's, BK and Byron.
3 (or anything else) I should see: Jacks, MacD's, BK and Byron.
If i understood correctly, the table user_hidden_list mantains a relation between one user and the users he can't see. So for, example, user with id equal to 1 (matching on column userid) can't see users 1 and 2 (matching on column est_id).
So, for a particular user with ID = X, we can get the ID list of user he can't see like next:
SELECT
est_id
FROM
user_hidden_list
WHERE
userid = X AND hidden = 1;
Using the previous query, we can get the visible users for user X like on next query:
SELECT
tl.id, tl.name, tl.locale
FROM
theList AS tl
WHERE
tl.id NOT IN (SELECT est_id
FROM user_hidden_list
WHERE userid = X AND hidden = 1);
I'm sure there will be a better (elegant) way to do this, but i'm just leaving work and my mind is not working nice now.
I am trying to display all results except where in Table 2 both the userid column equals 1 and the hidden column equals 1.
This does not suggest an outer join. You seem to want:
SELECT tl.id, tl.name, tl.locale, uh.hidden
FROM theList tl JOIN
user_hidden_list uh
ON uh.est_id = tl.id
WHERE NOT (uh.userid = 1 AND uh.hidden = 1);
I am guessing that userid and hidden are numbers of some sort, so I removed the single quotes. If they are really strings, then use the single quotes.
This also assumes that these values cannot be NULL. If that is a possibility, then the logic can be adjusted (using the null-safe comparator <=>).
Try out this, with even parantheses:
SELECT tl.id, tl.name, tl.locale, uh.hidden
FROM theList tl JOIN
user_hidden_list uh
ON uh.est_id = tl.id
WHERE (uh.userid <> 1 AND uh.hidden <> 1);
The ideia is: select all professions from a table. After this count how many professionals have the profession id in his category column. The category column store the professions id's separeted by commas (1, 2, 3, 420). The professions table has 604 rows.
I have the following piece of code:
<?php
$select_professions = mysql_query("SELECT * FROM professions");
if(mysql_num_rows($select_professions) == "0"){
echo"No registers in DB";
}else{while($row_professions = mysql_fetch_assoc($select_professions)){
$id = $row_professions['id'];
$count_profiles = mysql_query("SELECT
COUNT(FIND_IN_SET(professions.id, professional.category) > 0) AS profile_numbers
FROM
professions
INNER JOIN
professional
WHERE
FIND_IN_SET(professions.id,professional.category) > 0
AND
professions.id = $id
GROUP BY
professions.id");
$reg_profiles = mysql_fetch_assoc($count_profiles);
$numProfiles = $reg_profiles['profile_numbers'];
if($numProfiles > 4){
$style = 'display:none';
}else{
$style = '';
}
?>
My basic question is WHY this is so slow in Google Chrome?
Its taking like 15 seconds to load entire page with these results in a html table. In Edge or Firefox is taking about 5 seconds. I heard about Chrome using so much memory lately but I don't believe its soo slowly. In time this is the first time I use the FIND_IN_SET function on mysql. Is that may are slowing down the request? Anyone knows what I'm doing wrong or how can be optimized? This is actualy working but we know that 15 seconds of waiting makes the user give up or think that page is not working. I have to say too that if I do the same consultation on my HeidiSQL it takes 1 second.
I recommend to normalize this:
The category column store the professions id's separeted by commas (1,
2, 3, 420)
This is an n:n relationship. Your layout:
professionals:
id | catgeory
12 | 1,2,4,50
professions
id | desc
1 | prof A
2 | prof B
...
The string operations (split the list, normalize internal, query result in to temp, ...) is very cost intensive. Better:
professionals:
id | ...
12 | ..
profrelations
pid | cid
12 | 1
12 | 2
12 | 4
12 | 50
professions
id | desc
1 | prof A
2 | prof B
...
This would skip the COUNT(FIND_IN_SET(professions.id, professional.category) > 0) as a string operation (even twice):
SELECT COUNT(cid) AS profile_numbers from professionals, profrelations where
professionals.id = profrelations.pid AND profrelations.pid = $id;
etc. You might restructure the above query like this, as long as you won't actually need any column from professions.
You can add a unique index on the cols (pid, cid) in table profrelations as one professional actually can have one profession only one times.
Remark
The different behaviour in two browser might result from the server caching the query: You're doing the query with Chrome, it's slow, but the result gets cached. Next with FF, server will respond with the cached result as its the same query again - fast. Try it three times or the other way round, should then be the same in all browsers.
At first,
this operation COUNT(FIND_IN_SET(professions.id, professional.category) > 0) will not return result that you expected. Count in above expression will return 1 even if find_in_set returns 0.
Secondly, I wouldn't use join in this case at all. This tables have no direct relation by identifiers.
I would optimize the query as following:
SELECT COUNT(professions.id) AS profile_numbers FROM professions, professional
WHERE FIND_IN_SET(professions.id,professional.category) > 0 AND professions.id = $id
GROUP BY professions.id
My ch_skills table looks like
uid | skill1 | skill2 | skill3 | skill4 | skill5
1 1 2 2 0 1
2 1 1 2 1 1
3 1 2 3 0 1
My first question: is this correct? I mean would it be better if I made it like this:
uid | skillid | skill_lvl
1 1 1
1 2 2
1 3 2
1 4 0
1 5 1
Everything worked fine until now with the example #1, but now I'm in a trouble with the sql queries. Currently, I'm using 5 different queries to get the level of each skill. I use the following code:
For skill1:
$query = $this->db->prepare("SELECT `skills`.`skill_ID` as `Skill1_id`,
`skill_name`.`skill_name` as `Skill1_name`, `skill_level` as `Skill1_level`,
`skill_price` as `Skill1_price`
FROM `skills`, `skill_name`, `ch_skills`
WHERE `skill_name`.`skill_ID` = `skills`.`skill_ID`
AND `skills`.`skill_ID`= 1
AND `skills`.`skill_level` = `ch_skills`.`skill1`
AND `ch_skills`.`uid` = :uid");
For skill2:
$query = $this->db->prepare("SELECT `skills`.`skill_ID` as `Skill1_id`,
`skill_name`.`skill_name` as `Skill1_name`, `skill_level` as `Skill1_level`,
`skill_price` as `Skill1_price`
FROM `skills`, `skill_name`, `ch_skills`
WHERE `skill_name`.`skill_ID` = `skills`.`skill_ID`
AND `skills`.`skill_ID`= 2
AND `skills`.`skill_level` = `ch_skills`.`skill2`
AND `ch_skills`.`uid` = :uid");
And so on... As you can see, there's only two differences: skill_id = 2, and skill2 as the coulmn's name. Is there any way for querying all the 5 skills in only 1 query? Or would you recommend me anyway to change the table structure?
Note: skills stands for the skill prices, and skill_name for the skill's names.
As the other commenters have suggested, your best choice is to change the table exactly as you proposed.
The biggest reason not to have a wide table like you show in your first example, is that adding a skill means changing the structure of the database, which could break existing queries.
Secondly, as you see when you're trying to query the results, having a single table doesn't even make it easier to work with.
The only possible benefit to a non-normalized table like your example is that it takes up slightly less disk space. But in todays world, disk space should never be your primary concern.
To answer your question about querying the original non-normalized example, however, there are two ways to do it:
Use a union statement which would combine 5 distinct queries together. This is pretty inefficient
Create a table with (in this case) 5 rows (or if you have a Skills table use that). Then join the ch_skills table to that, which should take each row and split it 5 times. See below: (note: I'm assuming for the purposes of this example that skills and skill_name are in a 1:1 relationship and only have 5 records each)
SELECT skills.skill_ID,
skill_name.skill_name,
skill_level as Skill_level,
skill_price as Skill_price
FROM skills
JOIN skill_name on skill_name.skill_ID = skills.skill_ID
JOIN ch_skills
WHERE ch_skills.uid = :uid
AND ((skills.skill_ID = 1 AND skills.skill_level = ch_skills.skill1)
OR (skills.skill_ID = 2 AND skills.skill_level = ch_skills.skill2)
OR (skills.skill_ID = 3 AND skills.skill_level = ch_skills.skill3)
OR (skills.skill_ID = 4 AND skills.skill_level = ch_skills.skill4)
OR (skills.skill_ID = 5 AND skills.skill_level = ch_skills.skill5))
I m trying to create ID like "A1 , A2, A3 .. etc
So i tried like this
$q = mysql_query("SELECT merge_id FROM merge_info ORDER BY merge_id DESC LIMIT 1;");
$s = mysql_fetch_array($q);
$merge_id5 = $s['merge_id'];
$count2=mysql_num_rows($q);
if($count2>0)
{
$merge_id5 = explode("A",$merge_id5);
$mergeid_no = $merge_id5[1]+1;
$merge_id6 = $mergeid_no;
}
else
{
$merge_id6 ="1";
}
if($count<1)
{
$merge_id = $merge_id5;
}
Everything is working fine... but after creating A9, it create A10 then again it creates A10 not moving to A11 , A12 . etc., i think if i write correct query to fetch last inserted row i'll fix this issue
Please someone help me
db table :
merge_id | name |
A1 | xxxx |
A2 | yyyy |
A3 | zzzz |
....
....
A9 | sds |
A10 | dsfs |
i know it is not the best solution to your problem, but this will help you.
and just get the first record because if i add LIMIT 1 the output is wrong :(
SELECT * FROM merge_info ORDER BY LENGTH(merge_id) DESC
Change your query to:-
SELECT MAX(merge_id) FROM merge_info;
I think it's better you use an auto_increment field, to get the last insert row with LAST_INSERT_ID(), otherwise you can't be sure if the last row, the one you have inserted.
So long. To order with your solution, use this.
ORDER BY SUBSTRING(merge_id,2) DESC
Better approach to your problem could be ,
use AUTO_INCREMENT field and while displaying append 'A' to it.
Now to solve this you can use below SQL statement
SELECT * FROM `merge_info` ORDER BY SUBSTRING(merge_id,2) DESC limit 1
should change you merge_id column into auto increment column,and the change your query into below mentioned,
SELECT MAX(merge_id) FROM merge_info;
if you want id like A1,A2,A3 ... then you can use the below code for get it
$q = mysql_query("SELECT merge_id FROM merge_info ORDER BY merge_id DESC LIMIT 1;");
$s = mysql_fetch_array($q);
$merge_id5 = $s['merge_id'];
$count2=mysql_num_rows($q);
$merge_id="A".$merge_id5;
after above process,noe we have a meger_id like A1,A2.. on application side