Get all rows not matching with another table - php

I've a tricky question. I have a table with numbers:
37823782
37823782
37823782
38478934
90003922
And another table with prefixes:
378
3847
384
001
I want to find all numbers matching the longest prefix. I succeded with this code:
$result = mysql_query("SELECT numbers FROM table1 GROUP BY numbers") or die ("Query error code 1");
while($row = mysql_fetch_array($result))
{
$numbers =$row["numbers"];
$result2 = mysql_query("SELECT * FROM table2 WHERE '".$numbers."' LIKE CONCAT(prefix, '%') ORDER BY CHAR_LENGTH(prefix) DESC LIMIT 1");
while($row2 = mysql_fetch_array($result2))
{
// That's it
}
}
Now what i want to simply make the opposite thing. I want to find all numbers not matching any prefix. In short in the above example i made i should get "90003922". I thought to use NOT LIKE CONCAT (prefix, '%') but it's not working. Any idea?

You can try this
SELECT * FROM table2 WHERE '".$numbers."' NOT LIKE 'prefix%'

One-query solution will look like this. Try it
SELECT * FROM table1 LEFT JOIN table2 ON table1.numbers LIKE CONCAT(table2.prefix,'%') WHERE table2.prefix IS NULL

Related

Counting the number of times each variable appears in table

Basically, I am seeking to know if there is a better way to accomplish this specific task.
Basically, what happens is I query the db for a list of "project needs" -- These are each uniquer and only appear once.
Then, I search another table to find out how many members have the required "skills - which are directly correlated to the project needs".
I accomplished exactly what I was trying to do by running a second query and then inserting them into an array like this:
function countEachSkill(){
$return = array();
$query = "SELECT DISTINCT SKILL_ID, SKILL_NAME FROM PROJECT_NEEDS";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);
while($row = mysql_fetch_assoc($result)){
$query = "SELECT COUNT(*) as COUNT FROM MEMBER_SKILLS WHERE SKILL_ID = '".$row['NEED_ID']."'";
$cResult = mysql_query($query);
$cRow = mysql_fetch_assoc($cResult);
$return[$row['SKILL_ID']]['Count'] = $cRow['COUNT'];
$return[$row['SKILL_ID']]['Name'] = $row['SKILL_NAME'];
}
arsort($return);
return $return;
}
But I feel like there has to be a better way (perhaps using some kind of join?) that would return this in a result set to avoid using the array.
Thanks in advance.
PS. I know mysql_ is depreciated. It is not my choice on which to use.
SELECT P.SKILL_ID, P.SKILL_NAME, COUNT(M.SKILL_ID) as COUNT FROM PROJECT_NEEDS P INNER JOIN MEMBER_SKILLS M
ON P.SKILL_ID=M.SKILL_ID
GROUP BY P.SKILL_ID, P.SKILL_NAME
I've adjusted Nriddens answer to accomodate for the select distinct, Im under the belief that his adjustment would be ok given SKILL_ID is a primary key
function countEachSkill(){
$return = array();
$query = "
SELECT
COUNT(*) AS COUNT,
PROJECT_NEEDS.SKILL_NAME,
PROJECT_NEEDS.SKILL_ID
FROM
(SELECT DISTINCT
SKILL_ID, SKILL_NAME
FROM
PROJECT_NEEDS) AS PROJECT_NEEDS
INNER JOIN
MEMBER_SKILLS
ON
MEMBER_SKILLS.SKILL_ID = PROJECT_NEEDS.SKILL_ID
GROUP BY PROJECT_NEEDS.SKILL_ID";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);
while($row = mysql_fetch_assoc($result)){
$return[$row['SKILL_ID']]['Count'] = $row['COUNT'];
$return[$row['SKILL_ID']]['Name'] = $row['SKILL_NAME'];
}
arsort($return);
return $return;
I am subquerying on the select distinct because I dont believe you have a dedicated skills table with an auto inc primary key, if that was there I wouldn't be using a subquery.
Can you test this query
select project_needs.*,count(members_skills.*) as count from project_needs
inner join members_skills
on members_skills.skill_id=project_needs.skill_id Group by project_needs.skill_name, project_needs.skill_id

SQL LEFT JOIN without duplicating same row values

I was wondering if someone can help me with my problem that is as follows:
I want to pull once posts.text and uids which belongs to that posts.text but when I execute the code below it does this: eg. there are 4 uids that belongs to the post so I get the posts.text four times instead of once.
$query = mysqli_query($con,
"SELECT posts.text, relationships.uidb
FROM posts
LEFT JOIN relationships
ON posts.uid=relationships.uida
LIMIT 10");
if(mysqli_num_rows($query) > 0){
while($row = mysqli_fetch_assoc($query)){
echo $row['text']." ".$row['uidb']."<br>";
}
}
I would really appreciate any help.
Thanks is advance.
Peter
Update:
Desired output would be like this:
postsArray[0]->text = //post text
postsArray[1]->text = //another post text
postsArray[0]->uids[0] = //approved uid for first post
postsArray[0]->uids[1] = //another approved uid for first post
now it outputs this:
text 10
text 15
text 12
and I want this:
text 10, 15, 12
One way is to use Mysql's GROUP_CONCAT which provides comma separated values list for each group i.e (p.uid)
$query = mysqli_query($con,
"SELECT p.text, GROUP_CONCAT(r.uidb SEPARATOR ', ') uidbs
FROM posts p
LEFT JOIN relationships r
ON p.uid=r.uida
GROUP BY p.uid
LIMIT 10");
if (mysqli_num_rows($query) > 0) {
while ($row = mysqli_fetch_assoc($query)) {
echo $row['text'].' '.$row['uidbs'];
/*$uidbs= explode($row['uidbs'],',');
foreach ($uidbs as $key => $val) {
echo $val.' ';
}*/
echo '</br>';
}
}
GROUP_CONCAT
According to docs The result is truncated to the maximum length that
is given by the group_concat_max_len system variable, which has a
default value of 1024. The value can be set higher, although the
effective maximum length of the return value is constrained by the
value of max_allowed_packet.
Maybe this might work for you:
$query = mysqli_query($con,
"SELECT posts.text, relationships.uidb
FROM posts
LEFT JOIN relationships
ON posts.uid=relationships.uida
GROUP BY posts.uid
LIMIT 10");
if(mysqli_num_rows($query) > 0){
while($row = mysqli_fetch_assoc($query)){
echo $row['text']." ".$row['uidb']."<br>";
}
}
SELECT posts.text, relationships.uidb
FROM posts
LEFT JOIN relationships
ON posts.uid=relationships.uida
GROUP BY posts.primary_key_of_your_post
LIMIT 10
You should call 2 queries. In your first query, call the text, and then call uids.
You should not write complex queries because this will make your business more complex and you will not maintain your code in future.

SQL SELECT query echoing twice even with DISTINCT

I am creating a simple SQL query in PHP - and for some reason, even when DISTINCT is used, it shows twice like this:
BC
BC
OH
OH
TX
TX
Here is my code:
<?php
$sql = "SELECT DISTINCT `title`,`extra_fields_search` FROM `blahblah_items` WHERE catid=336 ORDER BY `blahblah_items`.`extra_fields_search` ASC ";
$partnerlisting= mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($partnerlisting))
foreach($row as $cname => $cvalue){
echo '<li>'.substr($row[extra_fields_search], 0, 2).'</li><br>';
}
;
?>
How can I make it so it prints out only one of each?
SELECT
`title`,
`extra_fields_search`
FROM
`blahblah_items`
WHERE
catid=336
GROUP BY
SUBSTRING(extra_fields_search,1,2) # here. group by first two characters of extra_fields_search
# or just "GROUP BY extra_fields_search", depends what you need
ORDER BY
`blahblah_items`.`extra_fields_search` ASC
SELECT DISTINCT a,b FROM table works in same way as SELECT a,b FROM table GROUP BY a,b
Please follow documentation:
http://dev.mysql.com/doc/refman/5.0/en/distinct-optimization.html
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html
Distinct make sure that you get unique rows. It does not make sure you will get unique column values. In your case if you consider all the fields in the result, you will notice that each row is different from the other by at least one field.
SO you will never get
Col1 Col2
A B
A B
But you can get
Col1 Col2
A B
A C
Try:
SELECT `title`, group_concat(distinct `extra_fields_search`)
FROM `blahblah_items`
WHERE catid=336
Group BY `title`
ORDER BY 2
try this
SELECT `title`,`extra_fields_search`
FROM `blahblah_items` WHERE catid=336
Group BY extra_fields_search
ORDER BY `blahblah_items`.`extra_fields_search` ASC
edit :
try this in your code
while($row = mysql_fetch_assoc($partnerlisting))
$rows[] = $row;
foreach($rows as $row){
echo '<li>'.substr($row[extra_fields_search], 0, 2).'</li><br>';
}
;

mysql + php: Selecting multiple random results

I've been looking for this for a while but with no success.
I am trying to implement a recomendation bar, for example like in youtube, when you are seeing a video it shows the list or recommended videos on the right.
At this moment I am using this method:
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `$tablename` ");
$offset_row = mysql_fetch_object($offset_result );
$offset = $offset_row->offset;
$result_rand = mysql_query( " SELECT * FROM `$tablename` LIMIT $offset, 9 " );
This works fine, but sometimes doesn't show any result, and the problem is also that its not completely random, because it shows for example the first ID as 200, so the next result will be id 201 and then 202 and so.
I would like to know if there is a way to show this 9 randon results, for example 1º result id 500, 2º result id 10, 3º result id 788, etc etc?
Thank you
Not entirely sure this answers what you are looking for, but try:
$result_rand = mysql_query("SELECT * FROM " . $tablename . " ORDER BY RAND() LIMIT 9");
You can use php rand() function to create 5 numbers and save them in an array:
http://php.net/manual/en/function.rand.php
<?php
$rand_array = array();
for($i=1;$i<5;$i++) {
$rand_array[$i] = rand(0,500);
}
?>
and after that create a query with every int with a foreach loop and work with your data.
<?php
foreach ($rand_array as $integer) {
$q = "SELECT * from $tablename WHERE id='$integer';";
}
?>
Does this helps?
First you should use mysqli_ functions instead of mysql_ because the latter is deprecated. Second use order by rand() to get random rows:
$rand_result = mysqli_query( "SELECT * FROM $tablename ORDER BY RAND() LIMIT 9;" );
UNTESTED:
SELECT id, #rownum:=#rownum+1 AS rownum, name
FROM users u,
(SELECT #rownum:=0) r
THis will give a unique number to each row in sequence. Now if you create a temp table with 9 random numbers between 1 and count(*) of your table and JOIN those two together...
Not sure about performance but seems like it might be faster than Rand and order by since I only need 9 random numbers

MySql return only one instance of duplicate entries

Hi I have a table with names and numbers entered along with other data . The table called events contains many instances where the name and numbers are the same but the other entries are different. I want to perform a search using names so I can display the number. But in my search I only need to return one instance of a name . The table is like this
Name Number Responisble Position
Paul 8455 Chorley t7
Dave 3821 PR south f5
Paul 8455 PR North p9
Paul 8455 Leyland t6
Dave 3821 Ribbleton r4
and my script is this
$condition = "name LIKE 'Paul' ";
$result = mysql_query("SELECT * FROM events WHERE $condition ") ;
while($row = mysql_fetch_array($result)) {
The script is not complete but I hope you can see that the results would return 3 results but what i want is a result with just one for each name
I hope this makes sense ! thanks for any help
$condition = "name LIKE 'Paul' ";
$result = mysql_query("SELECT * FROM events WHERE $condition GROUP BY name") ;
try using distinct -
SELECT DISTINCT (columns) FROM (table) WHERE (condition)
edit probably disregard this, mis-understood your question i think
MySql return only one instance of duplicate entries
You can either use group by or distinct in the select statement see http://dev.mysql.com/doc/refman/5.1/en/select.html
In your example it would be
$condition = "name LIKE 'Paul' ";
$result = mysql_query("SELECT * FROM events WHERE $condition GROUP BY name") ;
while($row = mysql_fetch_array($result)) {
SELECT name, number FROM events WHERE $condition GROUP BY name, number

Categories