10

I have the items in my data attribute table, which were selected. I want to make the object with the same value be selected in the attribute table, which belongs to another layer. In both cases, the considered column is called "new_name".

If for instance the "new_name" value has been selected in the left attribute table I need exactly the same value to be selected in the other attribute table.

enter image description here

How can I make a selection such as this?

1
  • 1
    I do remember. When everyone needs to wait for confirmation, I am not returning to the problem for a longer time. Sorry for making you frustrated. I do appreciate your answer and reward it right now. Thank you for being so helpful.
    – Geographos
    Commented Jul 3, 2023 at 8:53

2 Answers 2

10

I can suggest a PyQGIS solution.

Proceed with Plugins > Python Console > Show Editor and paste the script below

from qgis.core import QgsProject

layer1 = QgsProject.instance().mapLayersByName('Final cellsites')[0]
layer2 = QgsProject.instance().mapLayersByName('Lighting columns')[0]

field1 = "new_name"
field2 = "new_name"

selected_features = [feat[field1] for feat in layer1.selectedFeatures()]

selected_attributes = f'({selected_features[0]})' if len(selected_features) == 1 else tuple(selected_features)

expression = f'"{field2}" in {selected_attributes}'

layer2.selectByExpression(expression)

Press Run script run script and get the output that will look like

example


References:

8

You can use this expression in select by expression of layer2:

array_contains(
  aggregate(
    'layer1',
    'array_agg',
    "new_name",
    is_selected(
      'layer1',
      $currentfeature
    )
  ),
"new_name")

What it does:

aggregate() returns an array of of all new_name values of layer1. Using the filter:=is_selected('layer1',$currentfeature) it will only return those new_name values, which are currently selected in layer1. array_contains() then checks if the current new_name value of layer2 is in that array. If yes, it selects the feature.

2
  • No matching features found. However no error appear, which means we are nearly there
    – Geographos
    Commented Apr 14, 2022 at 10:02
  • @MKR make sure that you have features selected in layer1, execute this expression in layer2 and that both layers have the exact same attributes (take care of whitespaces and stuff like that) as well as the same fieldtypes. Dont forget to rename layernames and fieldnames to the ones you actually use. If it still does not work for you, feel free to share some example data.
    – MrXsquared
    Commented Apr 14, 2022 at 10:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.